4.9.320-rc1 review
Subsystems (5)
Greg Kroah-Hartman
maintainerPATCH 118/264 random: use RDSEED instead of RDRAND in entropy extraction
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 28f425e573e906a4c15f8392cc2b1561ef448595 upstream.
When /dev/random was directly connected with entropy extraction, without any expansion stage, extract_buf() was called for every 10 bytes of data read from /dev/random. For that reason, RDRAND was used rather than RDSEED. At the same time, crng_reseed() was still only called every 5 minutes, so there RDSEED made sense.
Those olden days were also a time when the entropy collector did not use a cryptographic hash function, which meant most bets were off in terms of real preimage resistance. For that reason too it didn't matter _that_ much whether RDSEED was mixed in before or after entropy extraction; both choices were sort of bad.
But now we have a cryptographic hash function at work, and with that we get real preimage resistance. We also now only call extract_entropy() every 5 minutes, rather than every 10 bytes. This allows us to do two important things.
First, we can switch to using RDSEED in extract_entropy(), as Dominik suggested. Second, we can ensure that RDSEED input always goes into the cryptographic hash function with other things before being used directly. This eliminates a category of attacks in which the CPU knows the current state of the crng and knows that we're going to xor RDSEED into it, and so it computes a malicious RDSEED. By going through our hash function, it would require the CPU to compute a preimage on the fly, which isn't going to happen.
--- drivers/char/random.c | 246 ++++++++++++-------------------------------------- 1 file changed, 62 insertions(+), 184 deletions(-)
drivers/char/random.c +62 -184
@@ -324,14 +324,11 @@ static struct crng_state primary_crng =* its value (from 0->1->2). */ static int crng_init =0 ; -static bool crng_need_final_init = false;#define crng_ready () (likely(crng_init > 1))static int crng_init_cnt =0 ; -static unsigned long crng_global_init_time =0 ;#define CRNG_INIT_CNT_THRESH (2 * CHACHA20_KEY_SIZE) -static void _extract_crng (struct crng_state *crng,u8 out[CHACHA20_BLOCK_SIZE ]); -static void _crng_backtrack_protect (struct crng_state *crng, -u8 tmp[CHACHA20_BLOCK_SIZE ],int used); +static void extract_crng (u8 out[CHACHA20_BLOCK_SIZE ]); +static void crng_backtrack_protect (u8 tmp[CHACHA20_BLOCK_SIZE ],int used);static void process_random_ready_list (void );static void _get_random_bytes (void *buf,int nbytes);
@@ -366,7 +363,7 @@ static struct {static void extract_entropy (void *buf,size_t nbytes); -static void crng_reseed (struct crng_state *crng); +static void crng_reseed (void );/* * This function adds bytes into the entropy "pool". It does not
@@ -465,7 +462,7 @@ static void credit_entropy_bits(int nbittrace_credit_entropy_bits (nbits, entropy_count, _RET_IP_);if (crng_init <2 && entropy_count >=POOL_MIN_BITS ) -crng_reseed (&primary_crng); +crng_reseed (); }/*********************************************************************
@@ -478,14 +475,6 @@ static void credit_entropy_bits(int nbitstatic DECLARE_WAIT_QUEUE_HEAD (crng_init_wait); -/* -* Hack to deal with crazy userspace progams when they are all trying -* to access /dev/urandom in parallel. The programs are almost -* certainly doing something terribly wrong, but we'll work around -* their brain damage. -*/ -static struct crng_state **crng_node_pool__read_mostly ; -static void invalidate_batched_entropy (void );static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU );
@@ -495,24 +484,6 @@ static int __init parse_trust_cpu(char * }early_param ("random.trust_cpu" , parse_trust_cpu); -static bool crng_init_try_arch (struct crng_state *crng) -{ -int i; -bool arch_init = true; -unsigned long rv; - -for (i =4 ; i <16 ; i++) { -if (!arch_get_random_seed_long (&rv) && - !arch_get_random_long (&rv)) { - rv =random_get_entropy (); - arch_init = false; - } - crng->state[i] ^= rv; - } - -return arch_init; -} -static bool __init crng_init_try_arch_early (void ) {int i;
@@ -531,100 +502,17 @@ static bool __init crng_init_try_arch_eareturn arch_init; } -static void crng_initialize_secondary (struct crng_state *crng) -{ -chacha_init_consts (crng->state); -_get_random_bytes (&crng->state[4 ],sizeof (u32) *12 ); -crng_init_try_arch (crng); - crng->init_time = jiffies -CRNG_RESEED_INTERVAL -1 ; -} - -static void __init crng_initialize_primary (void ) +static void __init crng_initialize (void ) {extract_entropy (&primary_crng.state[4 ],sizeof (u32) *12 );if (crng_init_try_arch_early () && trust_cpu && crng_init <2 ) {invalidate_batched_entropy (); -numa_crng_init (); crng_init =2 ;pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); } primary_crng.init_time = jiffies -CRNG_RESEED_INTERVAL -1 ; } -static void crng_finalize_init (void ) -{ -if (!system_wq) { -/* We can't call numa_crng_init until we have workqueues, -* so mark this for processing later. */ - crng_need_final_init = true; -return ; - } - -invalidate_batched_entropy (); -numa_crng_init (); - crng_init =2 ; - crng_need_final_init = false; -process_random_ready_list (); -wake_up_interruptible (&crng_init_wait); -kill_fasync (&fasync,SIGIO ,POLL_IN ); -pr_notice ("crng init done\n" ); -if (unseeded_warning.missed) { -pr_notice ("%d get_random_xx warning(s) missed due to ratelimiting\n" , - unseeded_warning.missed); - unseeded_warning.missed =0 ; - } -if (urandom_warning.missed) { -pr_notice ("%d urandom warning(s) missed due to ratelimiting\n" , - urandom_warning.missed); - urandom_warning.missed =0 ; - } -} - -static void do_numa_crng_init (struct work_struct *work) -{ -int i; -struct crng_state *crng; -struct crng_state **pool; - - pool =kcalloc (nr_node_ids,sizeof (*pool),GFP_KERNEL | __GFP_NOFAIL); -for_each_online_node (i) { - crng =kmalloc_node (sizeof (struct crng_state ), -GFP_KERNEL | __GFP_NOFAIL, i); -spin_lock_init (&crng->lock); -crng_initialize_secondary (crng); - pool[i] = crng; - } -/* pairs with READ_ONCE() in select_crng() */ -if (cmpxchg_release (&crng_node_pool,NULL , pool) !=NULL ) { -for_each_node (i) -kfree (pool[i]); -kfree (pool); - } -} - -static DECLARE_WORK(numa_crng_init_work, do_numa_crng_init); - -static void numa_crng_init (void ) -{ -if (IS_ENABLED (CONFIG_NUMA )) -schedule_work (&numa_crng_init_work); -} - -static struct crng_state *select_crng (void ) -{ -if (IS_ENABLED (CONFIG_NUMA )) { -struct crng_state **pool; -int nid =numa_node_id (); - -/* pairs with cmpxchg_release() in do_numa_crng_init() */ - pool =READ_ONCE (crng_node_pool); -if (pool && pool[nid]) -return pool[nid]; - } - -return &primary_crng; -} -/* * crng_fast_load() can be called by code in the interrupt service * path. So we can't afford to dilly-dally. Returns the number of
@@ -753,73 +641,71 @@ static int crng_slow_load(const u8 *cp,return 1 ; } -static void crng_reseed (struct crng_state *crng) +static void crng_reseed (void ) {unsigned long flags; -int i; +int i, entropy_count;union {u8 block[CHACHA20_BLOCK_SIZE ];u32 key[8 ]; } buf; -if (crng == &primary_crng) { -int entropy_count; -do { - entropy_count =READ_ONCE (input_pool.entropy_count); -if (entropy_count <POOL_MIN_BITS ) -return ; - }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); -extract_entropy (buf.key,sizeof (buf.key)); -wake_up_interruptible (&random_write_wait); -kill_fasync (&fasync,SIGIO ,POLL_OUT ); - }else { -_extract_crng (&primary_crng, buf.block); -_crng_backtrack_protect (&primary_crng, buf.block, -CHACHA20_KEY_SIZE ); - } -spin_lock_irqsave (&crng->lock, flags); -for (i =0 ; i <8 ; i++) { -unsigned long rv; -if (!arch_get_random_seed_long (&rv) && - !arch_get_random_long (&rv)) - rv =random_get_entropy (); - crng->state[i +4 ] ^= buf.key[i] ^ rv; - } +do { + entropy_count =READ_ONCE (input_pool.entropy_count); +if (entropy_count <POOL_MIN_BITS ) +return ; + }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); +extract_entropy (buf.key,sizeof (buf.key)); +wake_up_interruptible (&random_write_wait); +kill_fasync (&fasync,SIGIO ,POLL_OUT ); + +spin_lock_irqsave (&primary_crng.lock, flags); +for (i =0 ; i <8 ; i++) + primary_crng.state[i +4 ] ^= buf.key[i];memzero_explicit (&buf,sizeof (buf)); -WRITE_ONCE (crng->init_time, jiffies); -spin_unlock_irqrestore (&crng->lock, flags); -if (crng == &primary_crng && crng_init <2 ) -crng_finalize_init (); +WRITE_ONCE (primary_crng.init_time, jiffies); +spin_unlock_irqrestore (&primary_crng.lock, flags); +if (crng_init <2 ) { +invalidate_batched_entropy (); + crng_init =2 ; +process_random_ready_list (); +wake_up_interruptible (&crng_init_wait); +kill_fasync (&fasync,SIGIO ,POLL_IN ); +pr_notice ("crng init done\n" ); +if (unseeded_warning.missed) { +pr_notice ("%d get_random_xx warning(s) missed due to ratelimiting\n" , + unseeded_warning.missed); + unseeded_warning.missed =0 ; + } +if (urandom_warning.missed) { +pr_notice ("%d urandom warning(s) missed due to ratelimiting\n" , + urandom_warning.missed); + urandom_warning.missed =0 ; + } + } } -static void _extract_crng (struct crng_state *crng,u8 out[CHACHA20_BLOCK_SIZE ]) +static void extract_crng (u8 out[CHACHA20_BLOCK_SIZE ]) {unsigned long flags, init_time;if (crng_ready ()) { - init_time =READ_ONCE (crng->init_time); -if (time_after (READ_ONCE (crng_global_init_time), init_time) || -time_after (jiffies, init_time +CRNG_RESEED_INTERVAL )) -crng_reseed (crng); - } -spin_lock_irqsave (&crng->lock, flags); -chacha20_block (&crng->state[0 ], out); -if (crng->state[12 ] ==0 ) - crng->state[13 ]++; -spin_unlock_irqrestore (&crng->lock, flags); -} - -static void extract_crng (u8 out[CHACHA20_BLOCK_SIZE ]) -{ -_extract_crng (select_crng (), out); + init_time =READ_ONCE (primary_crng.init_time); +if (time_after (jiffies, init_time +CRNG_RESEED_INTERVAL )) +crng_reseed (); + } +spin_lock_irqsave (&primary_crng.lock, flags); +chacha20_block (&primary_crng.state[0 ], out); +if (primary_crng.state[12 ] ==0 ) + primary_crng.state[13 ]++; +spin_unlock_irqrestore (&primary_crng.lock, flags); }/* * Use the leftover bytes from the CRNG block output (if there is * enough) to mutate the CRNG key to provide backtracking protection. */ -static void _crng_backtrack_protect (struct crng_state *crng, -u8 tmp[CHACHA20_BLOCK_SIZE ],int used) +static void crng_backtrack_protect (u8 tmp[CHACHA20_BLOCK_SIZE ],int used) {unsigned long flags;u32 *s, *d;
@@ -830,17 +716,12 @@ static void _crng_backtrack_protect(struextract_crng (tmp); used =0 ; } -spin_lock_irqsave (&crng->lock, flags); +spin_lock_irqsave (&primary_crng.lock, flags); s = (u32 *)&tmp[used]; - d = &crng->state[4 ]; + d = &primary_crng.state[4 ];for (i =0 ; i <8 ; i++) *d++ ^= *s++; -spin_unlock_irqrestore (&crng->lock, flags); -} - -static void crng_backtrack_protect (u8 tmp[CHACHA20_BLOCK_SIZE ],int used) -{ -_crng_backtrack_protect (select_crng (), tmp, used); +spin_unlock_irqrestore (&primary_crng.lock, flags); }static ssize_t extract_crng_user (void __user *buf,size_t nbytes)
@@ -1105,16 +986,17 @@ static void extract_entropy(void *buf, sunsigned long flags;u8 seed[BLAKE2S_HASH_SIZE ], next_key[BLAKE2S_HASH_SIZE ];struct { -unsigned long rdrand[32 /sizeof (long )]; +unsigned long rdseed[32 /sizeof (long )];size_t counter; } block;size_t i;trace_extract_entropy (nbytes, input_pool.entropy_count); -for (i =0 ; i <ARRAY_SIZE (block.rdrand); ++i) { -if (!arch_get_random_long (&block.rdrand[i])) - block.rdrand[i] =random_get_entropy (); +for (i =0 ; i <ARRAY_SIZE (block.rdseed); ++i) { +if (!arch_get_random_seed_long (&block.rdseed[i]) && + !arch_get_random_long (&block.rdseed[i])) + block.rdseed[i] =random_get_entropy (); }spin_lock_irqsave (&input_pool.lock, flags);
@@ -1122,7 +1004,7 @@ static void extract_entropy(void *buf, s/* seed = HASHPRF(last_key, entropy_input) */ blake2s_final (&input_pool.hash, seed); -/* next_key = HASHPRF(seed, RDRAND || 0) */ +/* next_key = HASHPRF(seed, RDSEED || 0) */ block.counter =0 ;blake2s (next_key, (u8 *)&block, seed,sizeof (next_key),sizeof (block),sizeof (seed));blake2s_init_key (&input_pool.hash,BLAKE2S_HASH_SIZE , next_key,sizeof (next_key));
@@ -1132,7 +1014,7 @@ static void extract_entropy(void *buf, swhile (nbytes) { i =min_t (size_t, nbytes,BLAKE2S_HASH_SIZE ); -/* output = HASHPRF(seed, RDRAND || ++counter) */ +/* output = HASHPRF(seed, RDSEED || ++counter) */ ++block.counter;blake2s (buf, (u8 *)&block, seed, i,sizeof (block),sizeof (seed)); nbytes -= i;
@@ -1426,10 +1308,7 @@ static void __init init_std_data(void)int __init rand_initialize (void ) {init_std_data (); -if (crng_need_final_init) -crng_finalize_init (); -crng_initialize_primary (); - crng_global_init_time = jiffies; +crng_initialize ();if (ratelimit_disable) { urandom_warning.interval =0 ; unseeded_warning.interval =0 ;
@@ -1599,8 +1478,7 @@ static long random_ioctl(struct file *f,return -EPERM ;if (crng_init <2 )return -ENODATA ; -crng_reseed (&primary_crng); -WRITE_ONCE (crng_global_init_time, jiffies -1 ); +crng_reseed ();return 0 ;default :return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 119/264 random: inline leaves of rand_initialize()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 8566417221fcec51346ec164e920dacb979c6b5f upstream.
This is a preparatory commit for the following one. We simply inline the various functions that rand_initialize() calls that have no other callers. The compiler was doing this anyway before. Doing this will allow us to reorganize this after. We can then move the trust_cpu and parse_trust_cpu definitions a bit closer to where they're actually used, which makes the code easier to read.
--- drivers/char/random.c | 90 ++++++++++++++++++-------------------------------- 1 file changed, 33 insertions(+), 57 deletions(-)
drivers/char/random.c +33 -57
@@ -477,42 +477,6 @@ static DECLARE_WAIT_QUEUE_HEAD(crng_initstatic void invalidate_batched_entropy (void ); -static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU ); -static int __init parse_trust_cpu (char *arg) -{ -return kstrtobool (arg, &trust_cpu); -} -early_param ("random.trust_cpu" , parse_trust_cpu); - -static bool __init crng_init_try_arch_early (void ) -{ -int i; -bool arch_init = true; -unsigned long rv; - -for (i =4 ; i <16 ; i++) { -if (!arch_get_random_seed_long_early (&rv) && - !arch_get_random_long_early (&rv)) { - rv =random_get_entropy (); - arch_init = false; - } - primary_crng.state[i] ^= rv; - } - -return arch_init; -} - -static void __init crng_initialize (void ) -{ -extract_entropy (&primary_crng.state[4 ],sizeof (u32) *12 ); -if (crng_init_try_arch_early () && trust_cpu && crng_init <2 ) { -invalidate_batched_entropy (); - crng_init =2 ; -pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); - } - primary_crng.init_time = jiffies -CRNG_RESEED_INTERVAL -1 ; -} -/* * crng_fast_load() can be called by code in the interrupt service * path. So we can't afford to dilly-dally. Returns the number of
@@ -1272,17 +1236,28 @@ int __must_check get_random_bytes_arch(v }EXPORT_SYMBOL (get_random_bytes_arch); +static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU ); +static int __init parse_trust_cpu (char *arg) +{ +return kstrtobool (arg, &trust_cpu); +} +early_param ("random.trust_cpu" , parse_trust_cpu); +/* -* init_std_data - initialize pool with system data -* -* This function clears the pool's entropy count and mixes some system -* data into the pool to prepare it for use. The pool is not cleared -* as that can only decrease the entropy in the pool. +* Note that setup_arch() may call add_device_randomness() +* long before we get here. This allows seeding of the pools +* with some platform dependent data very early in the boot +* process. But it limits our options here. We must use +* statically allocated structures that already have all +* initializations complete at compile time. We should also +* take care not to overwrite the precious per platform data +* we were given. */ -static void __init init_std_data (void ) +int __init rand_initialize (void ) {int i;ktime_t now =ktime_get_real (); +bool arch_init = true;unsigned long rv;mix_pool_bytes (&now,sizeof (now));
@@ -1293,22 +1268,23 @@ static void __init init_std_data(void)mix_pool_bytes (&rv,sizeof (rv)); }mix_pool_bytes (utsname (),sizeof (*(utsname ()))); -} -/* -* Note that setup_arch() may call add_device_randomness() -* long before we get here. This allows seeding of the pools -* with some platform dependent data very early in the boot -* process. But it limits our options here. We must use -* statically allocated structures that already have all -* initializations complete at compile time. We should also -* take care not to overwrite the precious per platform data -* we were given. -*/ -int __init rand_initialize (void ) -{ -init_std_data (); -crng_initialize (); +extract_entropy (&primary_crng.state[4 ],sizeof (u32) *12 ); +for (i =4 ; i <16 ; i++) { +if (!arch_get_random_seed_long_early (&rv) && + !arch_get_random_long_early (&rv)) { + rv =random_get_entropy (); + arch_init = false; + } + primary_crng.state[i] ^= rv; + } +if (arch_init && trust_cpu && crng_init <2 ) { +invalidate_batched_entropy (); + crng_init =2 ; +pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); + } + primary_crng.init_time = jiffies -CRNG_RESEED_INTERVAL -1 ; +if (ratelimit_disable) { urandom_warning.interval =0 ; unseeded_warning.interval =0 ;
Greg Kroah-Hartman
maintainerPATCH 120/264 random: ensure early RDSEED goes through mixer on init
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a02cf3d0dd77244fd5333ac48d78871de459ae6d upstream.
Continuing the reasoning of "random: use RDSEED instead of RDRAND in entropy extraction" from this series, at init time we also don't want to be xoring RDSEED directly into the crng. Instead it's safer to put it into our entropy collector and then re-extract it, so that it goes through a hash function with preimage resistance. As a matter of hygiene, we also order these now so that the RDSEED byte are hashed in first, followed by the bytes that are likely more predictable (e.g. utsname()).
--- drivers/char/random.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-)
drivers/char/random.c +5 -11
@@ -1260,24 +1260,18 @@ int __init rand_initialize(void)bool arch_init = true;unsigned long rv; -mix_pool_bytes (&now,sizeof (now));for (i =BLAKE2S_BLOCK_SIZE ; i >0 ; i -=sizeof (rv)) { -if (!arch_get_random_seed_long (&rv) && - !arch_get_random_long (&rv)) - rv =random_get_entropy (); -mix_pool_bytes (&rv,sizeof (rv)); - } -mix_pool_bytes (utsname (),sizeof (*(utsname ()))); - -extract_entropy (&primary_crng.state[4 ],sizeof (u32) *12 ); -for (i =4 ; i <16 ; i++) {if (!arch_get_random_seed_long_early (&rv) && !arch_get_random_long_early (&rv)) { rv =random_get_entropy (); arch_init = false; } - primary_crng.state[i] ^= rv; +mix_pool_bytes (&rv,sizeof (rv)); } +mix_pool_bytes (&now,sizeof (now)); +mix_pool_bytes (utsname (),sizeof (*(utsname ()))); + +extract_entropy (&primary_crng.state[4 ],sizeof (u32) *12 );if (arch_init && trust_cpu && crng_init <2 ) {invalidate_batched_entropy (); crng_init =2 ;
Greg Kroah-Hartman
maintainerPATCH 121/264 random: do not xor RDRAND when writing into /dev/random
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 91c2afca290ed3034841c8c8532e69ed9e16cf34 upstream.
Continuing the reasoning of "random: ensure early RDSEED goes through mixer on init", we don't want RDRAND interacting with anything without going through the mixer function, as a backdoored CPU could presumably cancel out data during an xor, which it'd have a harder time doing when being forced through a cryptographic hash function. There's actually no need at all to be calling RDRAND in write_pool(), because before we extract from the pool, we always do so with 32 bytes of RDSEED hashed in at that stage. Xoring at this stage is needless and introduces a minor liability.
--- drivers/char/random.c | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-)
drivers/char/random.c +2 -12
@@ -1357,25 +1357,15 @@ static unsigned int random_poll(struct fstatic int write_pool (const char __user *buffer,size_t count) {size_t bytes; -u32 t, buf[16 ]; +u8 buf[BLAKE2S_BLOCK_SIZE ];const char __user *p = buffer;while (count >0 ) { -int b, i =0 ; - bytes =min (count,sizeof (buf)); -if (copy_from_user (&buf, p, bytes)) +if (copy_from_user (buf, p, bytes))return -EFAULT ; - -for (b = bytes; b >0 ; b -=sizeof (u32), i++) { -if (!arch_get_random_int (&t)) -break ; - buf[i] ^= t; - } - count -= bytes; p += bytes; -mix_pool_bytes (buf, bytes);cond_resched (); }
Greg Kroah-Hartman
maintainerPATCH 122/264 random: absorb fast pool into input pool after fast load
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit c30c575db4858f0bbe5e315ff2e529c782f33a1f upstream.
During crng_init == 0, we never credit entropy in add_interrupt_ randomness(), but instead dump it directly into the primary_crng. That's fine, except for the fact that we then wind up throwing away that entropy later when we switch to extracting from the input pool and xoring into (and later in this series overwriting) the primary_crng key. The two other early init sites -- add_hwgenerator_randomness()'s use crng_fast_load() and add_device_ randomness()'s use of crng_slow_load() -- always additionally give their inputs to the input pool. But not add_interrupt_randomness().
This commit fixes that shortcoming by calling mix_pool_bytes() after crng_fast_load() in add_interrupt_randomness(). That's partially verboten on PREEMPT_RT, where it implies taking spinlock_t from an IRQ handler. But this also only happens during early boot and then never again after that. Plus it's a trylock so it has the same considerations as calling crng_fast_load(), which we're already using.
--- drivers/char/random.c | 407 +++++++++++++++++++++++++++++--------------------- 1 file changed, 237 insertions(+), 170 deletions(-)
drivers/char/random.c +237 -170
@@ -67,63 +67,19 @@* Exported interfaces ---- kernel output * -------------------------------------- * -* The primary kernel interface is +* The primary kernel interfaces are: * * void get_random_bytes(void *buf, int nbytes); -* -* This interface will return the requested number of random bytes, -* and place it in the requested buffer. This is equivalent to a -* read from /dev/urandom. -* -* For less critical applications, there are the functions: -* * u32 get_random_u32() * u64 get_random_u64() * unsigned int get_random_int() * unsigned long get_random_long() * -* These are produced by a cryptographic RNG seeded from get_random_bytes, -* and so do not deplete the entropy pool as much. These are recommended -* for most in-kernel operations *if the result is going to be stored in -* the kernel*. -* -* Specifically, the get_random_int() family do not attempt to do -* "anti-backtracking". If you capture the state of the kernel (e.g. -* by snapshotting the VM), you can figure out previous get_random_int() -* return values. But if the value is stored in the kernel anyway, -* this is not a problem. -* -* It *is* safe to expose get_random_int() output to attackers (e.g. as -* network cookies); given outputs 1..n, it's not feasible to predict -* outputs 0 or n+1. The only concern is an attacker who breaks into -* the kernel later; the get_random_int() engine is not reseeded as -* often as the get_random_bytes() one. -* -* get_random_bytes() is needed for keys that need to stay secret after -* they are erased from the kernel. For example, any key that will -* be wrapped and stored encrypted. And session encryption keys: we'd -* like to know that after the session is closed and the keys erased, -* the plaintext is unrecoverable to someone who recorded the ciphertext. -* -* But for network ports/cookies, stack canaries, PRNG seeds, address -* space layout randomization, session *authentication* keys, or other -* applications where the sensitive data is stored in the kernel in -* plaintext for as long as it's sensitive, the get_random_int() family -* is just fine. -* -* Consider ASLR. We want to keep the address space secret from an -* outside attacker while the process is running, but once the address -* space is torn down, it's of no use to an attacker any more. And it's -* stored in kernel data structures as long as it's alive, so worrying -* about an attacker's ability to extrapolate it from the get_random_int() -* CRNG is silly. -* -* Even some cryptographic keys are safe to generate with get_random_int(). -* In particular, keys for SipHash are generally fine. Here, knowledge -* of the key authorizes you to do something to a kernel object (inject -* packets to a network connection, or flood a hash table), and the -* key is stored with the object being protected. Once it goes away, -* we no longer care if anyone knows the key. +* 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 get_random_{u32,u64,int,long}() family +* of functions may be higher performance for one-off random integers, +* because they do a bit of buffering. * * prandom_u32() * -------------
@@ -301,20 +257,6 @@ static struct fasync_struct *fasync;static DEFINE_SPINLOCK (random_ready_list_lock);static LIST_HEAD (random_ready_list); -struct crng_state { -u32 state[16 ]; -unsigned long init_time; -spinlock_t lock; -}; - -static struct crng_state primary_crng = { - .lock =__SPIN_LOCK_UNLOCKED (primary_crng.lock), - .state[0 ] =CHACHA_CONSTANT_EXPA , - .state[1 ] =CHACHA_CONSTANT_ND_3 , - .state[2 ] =CHACHA_CONSTANT_2_BY , - .state[3 ] =CHACHA_CONSTANT_TE_K , -}; -/* * crng_init = 0 --> Uninitialized * 1 --> Initialized
@@ -326,9 +268,6 @@ static struct crng_state primary_crng =static int crng_init =0 ;#define crng_ready () (likely(crng_init > 1))static int crng_init_cnt =0 ; -#define CRNG_INIT_CNT_THRESH (2 * CHACHA20_KEY_SIZE) -static void extract_crng (u8 out[CHACHA20_BLOCK_SIZE ]); -static void crng_backtrack_protect (u8 tmp[CHACHA20_BLOCK_SIZE ],int used);static void process_random_ready_list (void );static void _get_random_bytes (void *buf,int nbytes);
@@ -471,7 +410,28 @@ static void credit_entropy_bits(int nbit* *********************************************************************/ -#define CRNG_RESEED_INTERVAL (300 * HZ) +enum { +CRNG_RESEED_INTERVAL =300 *HZ , +CRNG_INIT_CNT_THRESH =2 *CHACHA20_KEY_SIZE +}; + +static struct { +u8 key[CHACHA20_KEY_SIZE ]__aligned(__alignof__(long)) ; +unsigned long birth; +unsigned long generation; +spinlock_t lock; +} base_crng = { + .lock =__SPIN_LOCK_UNLOCKED (base_crng.lock) +}; + +struct crng { +u8 key[CHACHA20_KEY_SIZE ]; +unsigned long generation; +}; + +static DEFINE_PER_CPU(struct crng, crngs) = { + .generation =ULONG_MAX +};static DECLARE_WAIT_QUEUE_HEAD (crng_init_wait);
@@ -488,22 +448,22 @@ static size_t crng_fast_load(const u8 *cu8 *p;size_t ret =0 ; -if (!spin_trylock_irqsave (&primary_crng.lock, flags)) +if (!spin_trylock_irqsave (&base_crng.lock, flags))return 0 ;if (crng_init !=0 ) { -spin_unlock_irqrestore (&primary_crng.lock, flags); +spin_unlock_irqrestore (&base_crng.lock, flags);return 0 ; } - p = (u8 *)&primary_crng.state[4 ]; + p = base_crng.key;while (len >0 && crng_init_cnt <CRNG_INIT_CNT_THRESH ) { - p[crng_init_cnt %CHACHA20_KEY_SIZE ] ^= *cp; + p[crng_init_cnt %sizeof (base_crng.key)] ^= *cp; cp++; crng_init_cnt++; len--; ret++; }if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) {invalidate_batched_entropy (); crng_init =1 ; } -spin_unlock_irqrestore (&primary_crng.lock, flags); +spin_unlock_irqrestore (&base_crng.lock, flags);if (crng_init ==1 )pr_notice ("fast init done\n" );return ret;
@@ -579,14 +539,14 @@ static int crng_slow_load(const u8 *cp,unsigned long flags;static u8 lfsr =1 ;u8 tmp; -unsigned int i, max =CHACHA20_KEY_SIZE ; +unsigned int i, max =sizeof (base_crng.key);const u8 *src_buf = cp; -u8 *dest_buf = (u8 *)&primary_crng.state[4 ]; +u8 *dest_buf = base_crng.key; -if (!spin_trylock_irqsave (&primary_crng.lock, flags)) +if (!spin_trylock_irqsave (&base_crng.lock, flags))return 0 ;if (crng_init !=0 ) { -spin_unlock_irqrestore (&primary_crng.lock, flags); +spin_unlock_irqrestore (&base_crng.lock, flags);return 0 ; }if (len > max)
@@ -597,38 +557,50 @@ static int crng_slow_load(const u8 *cp, lfsr >>=1 ;if (tmp &1 ) lfsr ^=0xE1 ; - tmp = dest_buf[i %CHACHA20_KEY_SIZE ]; - dest_buf[i %CHACHA20_KEY_SIZE ] ^= src_buf[i % len] ^ lfsr; + tmp = dest_buf[i %sizeof (base_crng.key)]; + dest_buf[i %sizeof (base_crng.key)] ^= src_buf[i % len] ^ lfsr; lfsr += (tmp <<3 ) | (tmp >>5 ); } -spin_unlock_irqrestore (&primary_crng.lock, flags); +spin_unlock_irqrestore (&base_crng.lock, flags);return 1 ; }static void crng_reseed (void ) {unsigned long flags; -int i, entropy_count; -union { -u8 block[CHACHA20_BLOCK_SIZE ]; -u32 key[8 ]; - } buf; +int entropy_count; +unsigned long next_gen; +u8 key[CHACHA20_KEY_SIZE ]; +/* +* First we make sure we have POOL_MIN_BITS of entropy in the pool, +* and then we drain all of it. Only then can we extract a new key. +*/ do { entropy_count =READ_ONCE (input_pool.entropy_count);if (entropy_count <POOL_MIN_BITS )return ; }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); -extract_entropy (buf.key,sizeof (buf.key)); +extract_entropy (key,sizeof (key));wake_up_interruptible (&random_write_wait);kill_fasync (&fasync,SIGIO ,POLL_OUT ); -spin_lock_irqsave (&primary_crng.lock, flags); -for (i =0 ; i <8 ; i++) - primary_crng.state[i +4 ] ^= buf.key[i]; -memzero_explicit (&buf,sizeof (buf)); -WRITE_ONCE (primary_crng.init_time, jiffies); -spin_unlock_irqrestore (&primary_crng.lock, flags); +/* +* 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); +WRITE_ONCE (base_crng.birth, jiffies); +spin_unlock_irqrestore (&base_crng.lock, flags); +memzero_explicit (key,sizeof (key)); +if (crng_init <2 ) {invalidate_batched_entropy (); crng_init =2 ;
@@ -649,77 +621,143 @@ static void crng_reseed(void) } } -static void extract_crng (u8 out[CHACHA20_BLOCK_SIZE ]) +/* +* The general form here is based on a "fast key erasure RNG" from +* <https://blog.cr.yp.to/20170723-random.html>. It generates a ChaCha +* block using the provided key, and then immediately overwites 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. +*/ +static void crng_fast_key_erasure (u8 key[CHACHA20_KEY_SIZE ], +u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)], +u8 *random_data,size_t random_data_len) { -unsigned long flags, init_time; +u8 first_block[CHACHA20_BLOCK_SIZE ]; -if (crng_ready ()) { - init_time =READ_ONCE (primary_crng.init_time); -if (time_after (jiffies, init_time +CRNG_RESEED_INTERVAL )) -crng_reseed (); - } -spin_lock_irqsave (&primary_crng.lock, flags); -chacha20_block (&primary_crng.state[0 ], out); -if (primary_crng.state[12 ] ==0 ) - primary_crng.state[13 ]++; -spin_unlock_irqrestore (&primary_crng.lock, flags); +BUG_ON (random_data_len >32 ); + +chacha_init_consts (chacha_state); +memcpy (&chacha_state[4 ], key,CHACHA20_KEY_SIZE ); +memset (&chacha_state[12 ],0 ,sizeof (u32) *4 ); +chacha20_block (chacha_state, first_block); + +memcpy (key, first_block,CHACHA20_KEY_SIZE ); +memcpy (random_data, first_block +CHACHA20_KEY_SIZE , random_data_len); +memzero_explicit (first_block,sizeof (first_block)); }/* -* Use the leftover bytes from the CRNG block output (if there is -* enough) to mutate the CRNG key to provide backtracking protection. +* 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_backtrack_protect (u8 tmp[CHACHA20_BLOCK_SIZE ],int used) +static void crng_make_state (u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)], +u8 *random_data,size_t random_data_len) {unsigned long flags; -u32 *s, *d; -int i; +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, because +* this is what crng_{fast,slow}_load mutate during early init. +*/ +if (unlikely (!crng_ready ())) { +bool ready; + +spin_lock_irqsave (&base_crng.lock, flags); + ready =crng_ready (); +if (!ready) +crng_fast_key_erasure (base_crng.key, chacha_state, + random_data, random_data_len); +spin_unlock_irqrestore (&base_crng.lock, flags); +if (!ready) +return ; + } + +/* +* If the base_crng is more than 5 minutes old, we reseed, which +* in turn bumps the generation counter that we check below. +*/ +if (unlikely (time_after (jiffies,READ_ONCE (base_crng.birth) +CRNG_RESEED_INTERVAL ))) +crng_reseed (); + +local_irq_save (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_irq_restore (flags); +} + +static ssize_t get_random_bytes_user (void __user *buf,size_t nbytes) +{ +bool large_request = nbytes >256 ; +ssize_t ret =0 , len; +u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)]; +u8 output[CHACHA20_BLOCK_SIZE ]; + +if (!nbytes) +return 0 ; - used =round_up (used,sizeof (u32)); -if (used +CHACHA20_KEY_SIZE >CHACHA20_BLOCK_SIZE ) { -extract_crng (tmp); - used =0 ; - } -spin_lock_irqsave (&primary_crng.lock, flags); - s = (u32 *)&tmp[used]; - d = &primary_crng.state[4 ]; -for (i =0 ; i <8 ; i++) - *d++ ^= *s++; -spin_unlock_irqrestore (&primary_crng.lock, flags); -} - -static ssize_t extract_crng_user (void __user *buf,size_t nbytes) -{ -ssize_t ret =0 , i =CHACHA20_BLOCK_SIZE ; -u8 tmp[CHACHA20_BLOCK_SIZE ]__aligned(4) ; -int large_request = (nbytes >256 ); + len =min_t (ssize_t,32 , nbytes); +crng_make_state (chacha_state, output, len); + +if (copy_to_user (buf, output, len)) +return -EFAULT ; + nbytes -= len; + buf += len; + ret += len;while (nbytes) {if (large_request &&need_resched ()) { -if (signal_pending (current)) { -if (ret ==0 ) - ret = -ERESTARTSYS ; +if (signal_pending (current))break ; - }schedule (); } -extract_crng (tmp); - i =min_t (int, nbytes,CHACHA20_BLOCK_SIZE ); -if (copy_to_user (buf, tmp, i)) { +chacha20_block (chacha_state, output); +if (unlikely (chacha_state[12 ] ==0 )) + ++chacha_state[13 ]; + + len =min_t (ssize_t, nbytes,CHACHA20_BLOCK_SIZE ); +if (copy_to_user (buf, output, len)) { ret = -EFAULT ;break ; } - nbytes -= i; - buf += i; - ret += i; + nbytes -= len; + buf += len; + ret += len; } -crng_backtrack_protect (tmp, i); - -/* Wipe data just written to memory */ -memzero_explicit (tmp,sizeof (tmp)); +memzero_explicit (chacha_state,sizeof (chacha_state)); +memzero_explicit (output,sizeof (output));return ret; }
@@ -902,6 +940,10 @@ void add_interrupt_randomness(int irq) crng_fast_load((u8 *)fast_pool->pool, sizeof(fast_pool->pool)) > 0) { fast_pool->count =0 ; fast_pool->last = now; +if (spin_trylock (&input_pool.lock)) { +_mix_pool_bytes (&fast_pool->pool,sizeof (fast_pool->pool)); +spin_unlock (&input_pool.lock); + } }return ; }
@@ -1024,23 +1066,36 @@ static void _warn_unseeded_randomness(co*/ static void _get_random_bytes (void *buf,int nbytes) { -u8 tmp[CHACHA20_BLOCK_SIZE ]__aligned(4) ; +u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)]; +u8 tmp[CHACHA20_BLOCK_SIZE ]; +ssize_t len;trace_get_random_bytes (nbytes, _RET_IP_); -while (nbytes >=CHACHA20_BLOCK_SIZE ) { -extract_crng (buf); - buf +=CHACHA20_BLOCK_SIZE ; +if (!nbytes) +return ; + + len =min_t (ssize_t,32 , nbytes); +crng_make_state (chacha_state, buf, len); + nbytes -= len; + buf += len; + +while (nbytes) { +if (nbytes <CHACHA20_BLOCK_SIZE ) { +chacha20_block (chacha_state, tmp); +memcpy (buf, tmp, nbytes); +memzero_explicit (tmp,sizeof (tmp)); +break ; + } + +chacha20_block (chacha_state, buf); +if (unlikely (chacha_state[12 ] ==0 )) + ++chacha_state[13 ]; nbytes -=CHACHA20_BLOCK_SIZE ; + buf +=CHACHA20_BLOCK_SIZE ; } -if (nbytes >0 ) { -extract_crng (tmp); -memcpy (buf, tmp, nbytes); -crng_backtrack_protect (tmp, nbytes); - }else -crng_backtrack_protect (tmp,CHACHA20_BLOCK_SIZE ); -memzero_explicit (tmp,sizeof (tmp)); +memzero_explicit (chacha_state,sizeof (chacha_state)); }void get_random_bytes (void *buf,int nbytes)
@@ -1271,13 +1326,12 @@ int __init rand_initialize(void)mix_pool_bytes (&now,sizeof (now));mix_pool_bytes (utsname (),sizeof (*(utsname ()))); -extract_entropy (&primary_crng.state[4 ],sizeof (u32) *12 ); +extract_entropy (base_crng.key,sizeof (base_crng.key));if (arch_init && trust_cpu && crng_init <2 ) {invalidate_batched_entropy (); crng_init =2 ;pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); } - primary_crng.init_time = jiffies -CRNG_RESEED_INTERVAL -1 ;if (ratelimit_disable) { urandom_warning.interval =0 ;
@@ -1309,7 +1363,7 @@ static ssize_t urandom_read_nowarn(strucint ret; nbytes =min_t (size_t, nbytes,INT_MAX >>6 ); - ret =extract_crng_user (buf, nbytes); + ret =get_random_bytes_user (buf, nbytes);trace_urandom_read (8 * nbytes,0 , input_pool.entropy_count);return ret; }
@@ -1613,8 +1667,15 @@ static atomic_t batch_generation = ATOMIstruct batched_entropy {union { -u64 entropy_u64[CHACHA20_BLOCK_SIZE /sizeof (u64)]; -u32 entropy_u32[CHACHA20_BLOCK_SIZE /sizeof (u32)]; +/* +* 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) * CHACHA20_BLOCK_SIZE. +*/ +u64 entropy_u64[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u64))]; +u32 entropy_u32[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u32))]; };unsigned int position;int generation;
@@ -1622,13 +1683,13 @@ struct batched_entropy {/* * Get a random word for internal kernel use only. The quality of the random -* number is good as /dev/urandom, but there is no backtrack protection, with -* the goal of being quite fast and not depleting entropy. 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. +* number is 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. */ -static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64); +static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = { + .position =UINT_MAX +};u64 get_random_u64 (void ) {
@@ -1644,20 +1705,24 @@ u64 get_random_u64(void) batch =raw_cpu_ptr (&batched_entropy_u64); next_gen =atomic_read (&batch_generation); -if (batch->position %ARRAY_SIZE (batch->entropy_u64) ==0 || +if (batch->position >=ARRAY_SIZE (batch->entropy_u64) || next_gen != batch->generation) { -extract_crng ((u8 *)batch->entropy_u64); +_get_random_bytes (batch->entropy_u64,sizeof (batch->entropy_u64)); batch->position =0 ; batch->generation = next_gen; } - ret = batch->entropy_u64[batch->position++]; + ret = batch->entropy_u64[batch->position]; + batch->entropy_u64[batch->position] =0 ; + ++batch->position;local_irq_restore (flags);return ret; }EXPORT_SYMBOL (get_random_u64); -static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32); +static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = { + .position =UINT_MAX +};u32 get_random_u32 (void ) {
@@ -1673,14 +1738,16 @@ u32 get_random_u32(void) batch =raw_cpu_ptr (&batched_entropy_u32); next_gen =atomic_read (&batch_generation); -if (batch->position %ARRAY_SIZE (batch->entropy_u32) ==0 || +if (batch->position >=ARRAY_SIZE (batch->entropy_u32) || next_gen != batch->generation) { -extract_crng ((u8 *)batch->entropy_u32); +_get_random_bytes (batch->entropy_u32,sizeof (batch->entropy_u32)); batch->position =0 ; batch->generation = next_gen; } - ret = batch->entropy_u32[batch->position++]; + ret = batch->entropy_u32[batch->position]; + batch->entropy_u32[batch->position] =0 ; + ++batch->position;local_irq_restore (flags);return ret; }
Greg Kroah-Hartman
maintainerPATCH 123/264 random: use hash function for crng_slow_load()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 66e4c2b9541503d721e936cc3898c9f25f4591ff upstream.
Since we have a hash function that's really fast, and the goal of crng_slow_load() is reportedly to "touch all of the crng's state", we can just hash the old state together with the new state and call it a day. This way we dont need to reason about another LFSR or worry about various attacks there. This code is only ever used at early boot and then never again.
--- drivers/char/random.c | 163 +++++++++++++++++------------------------- include/linux/hw_random.h | 2 include/linux/random.h | 10 +- include/trace/events/random.h | 79 +++++++++----------- 4 files changed, 113 insertions(+), 141 deletions(-)
drivers/char/random.c +69 -94
@@ -69,7 +69,7 @@* * The primary kernel interfaces are: * -* void get_random_bytes(void *buf, int nbytes); +* void get_random_bytes(void *buf, size_t nbytes); * u32 get_random_u32() * u64 get_random_u64() * unsigned int get_random_int()
@@ -97,14 +97,14 @@* The current exported interfaces for gathering environmental noise * from the devices are: * -* void add_device_randomness(const void *buf, unsigned int size); +* void add_device_randomness(const void *buf, size_t size); * void add_input_randomness(unsigned int type, unsigned int code, * unsigned int value); * void add_interrupt_randomness(int irq); * void add_disk_randomness(struct gendisk *disk); -* void add_hwgenerator_randomness(const char *buffer, size_t count, +* void add_hwgenerator_randomness(const void *buffer, size_t count, * size_t entropy); -* void add_bootloader_randomness(const void *buf, unsigned int size); +* void add_bootloader_randomness(const void *buf, size_t size); * * add_device_randomness() is for adding data to the random pool that * is likely to differ between two devices (or possibly even per boot).
@@ -269,7 +269,7 @@ static int crng_init = 0;#define crng_ready () (likely(crng_init > 1))static int crng_init_cnt =0 ;static void process_random_ready_list (void ); -static void _get_random_bytes (void *buf,int nbytes); +static void _get_random_bytes (void *buf,size_t nbytes);static struct ratelimit_state unseeded_warning =RATELIMIT_STATE_INIT ("warn_unseeded_randomness" ,HZ ,3 );
@@ -291,7 +291,7 @@ MODULE_PARM_DESC(ratelimit_disable, "Disstatic struct {struct blake2s_state hash;spinlock_t lock; -int entropy_count; +unsigned int entropy_count; } input_pool = { .hash.h = {BLAKE2S_IV0 ^ (0x01010000 |BLAKE2S_HASH_SIZE ),BLAKE2S_IV1 ,BLAKE2S_IV2 ,BLAKE2S_IV3 ,BLAKE2S_IV4 ,
@@ -309,18 +309,12 @@ static void crng_reseed(void);* update the entropy estimate. The caller should call * credit_entropy_bits if this is appropriate. */ -static void _mix_pool_bytes (const void *in,int nbytes) +static void _mix_pool_bytes (const void *in,size_t nbytes) {blake2s_update (&input_pool.hash, in, nbytes); } -static void __mix_pool_bytes (const void *in,int nbytes) -{ -trace_mix_pool_bytes_nolock (nbytes, _RET_IP_); -_mix_pool_bytes (in, nbytes); -} - -static void mix_pool_bytes (const void *in,int nbytes) +static void mix_pool_bytes (const void *in,size_t nbytes) {unsigned long flags;
@@ -384,18 +378,18 @@ static void process_random_ready_list(vospin_unlock_irqrestore (&random_ready_list_lock, flags); } -static void credit_entropy_bits (int nbits) +static void credit_entropy_bits (size_t nbits) { -int entropy_count, orig; +unsigned int entropy_count, orig, add; -if (nbits <=0 ) +if (!nbits)return ; - nbits =min (nbits,POOL_BITS ); + add =min_t (size_t, nbits,POOL_BITS );do { orig =READ_ONCE (input_pool.entropy_count); - entropy_count =min (POOL_BITS , orig + nbits); + entropy_count = min_t(unsigned int, POOL_BITS, orig + add); }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig);trace_credit_entropy_bits (nbits, entropy_count, _RET_IP_);
@@ -442,10 +436,10 @@ static void invalidate_batched_entropy(v* path. So we can't afford to dilly-dally. Returns the number of * bytes processed from cp. */ -static size_t crng_fast_load (const u8 *cp,size_t len) +static size_t crng_fast_load (const void *cp,size_t len) {unsigned long flags; -u8 *p; +const u8 *src = (const u8 *)cp;size_t ret =0 ;if (!spin_trylock_irqsave (&base_crng.lock, flags))
@@ -454,10 +448,9 @@ static size_t crng_fast_load(const u8 *cspin_unlock_irqrestore (&base_crng.lock, flags);return 0 ; } - p = base_crng.key;while (len >0 && crng_init_cnt <CRNG_INIT_CNT_THRESH ) { - p[crng_init_cnt %sizeof (base_crng.key)] ^= *cp; - cp++; crng_init_cnt++; len--; ret++; + base_crng.key[crng_init_cnt %sizeof (base_crng.key)] ^= *src; + src++; crng_init_cnt++; len--; ret++; }if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) {invalidate_batched_entropy ();
@@ -527,42 +520,30 @@ static struct crng_state *select_crng(vo* all), and (2) it doesn't have the performance constraints of * crng_fast_load(). * -* So we do something more comprehensive which is guaranteed to touch -* all of the primary_crng's state, and which uses a LFSR with a -* period of 255 as part of the mixing algorithm. Finally, we do -* *not* advance crng_init_cnt since buffer we may get may be something -* like a fixed DMI table (for example), which might very well be -* unique to the machine, but is otherwise unvarying. +* So, we simply hash the contents in with the current key. Finally, +* we do *not* advance crng_init_cnt since buffer we may get may be +* something like a fixed DMI table (for example), which might very +* well be unique to the machine, but is otherwise unvarying. */ -static int crng_slow_load (const u8 *cp,size_t len) +static void crng_slow_load (const void *cp,size_t len) {unsigned long flags; -static u8 lfsr =1 ; -u8 tmp; -unsigned int i, max =sizeof (base_crng.key); -const u8 *src_buf = cp; -u8 *dest_buf = base_crng.key; +struct blake2s_state hash; + +blake2s_init (&hash,sizeof (base_crng.key));if (!spin_trylock_irqsave (&base_crng.lock, flags)) -return 0 ; +return ;if (crng_init !=0 ) {spin_unlock_irqrestore (&base_crng.lock, flags); -return 0 ; +return ; } -if (len > max) - max = len; -for (i =0 ; i < max; i++) { - tmp = lfsr; - lfsr >>=1 ; -if (tmp &1 ) - lfsr ^=0xE1 ; - tmp = dest_buf[i %sizeof (base_crng.key)]; - dest_buf[i %sizeof (base_crng.key)] ^= src_buf[i % len] ^ lfsr; - lfsr += (tmp <<3 ) | (tmp >>5 ); - } +blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); +blake2s_update (&hash, cp, len); +blake2s_final (&hash, base_crng.key); +spin_unlock_irqrestore (&base_crng.lock, flags); -return 1 ; }static void crng_reseed (void )
@@ -718,14 +699,15 @@ static void crng_make_state(u32 chacha_sstatic ssize_t get_random_bytes_user (void __user *buf,size_t nbytes) {bool large_request = nbytes >256 ; -ssize_t ret =0 , len; +ssize_t ret =0 ; +size_t len;u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)];u8 output[CHACHA20_BLOCK_SIZE ];if (!nbytes)return 0 ; - len =min_t (ssize_t,32 , nbytes); + len =min_t (size_t,32 , nbytes);crng_make_state (chacha_state, output, len);if (copy_to_user (buf, output, len))
@@ -745,7 +727,7 @@ static ssize_t get_random_bytes_user(voiif (unlikely (chacha_state[12 ] ==0 )) ++chacha_state[13 ]; - len =min_t (ssize_t, nbytes,CHACHA20_BLOCK_SIZE ); + len =min_t (size_t, nbytes,CHACHA20_BLOCK_SIZE );if (copy_to_user (buf, output, len)) { ret = -EFAULT ;break ;
@@ -783,7 +765,7 @@ struct timer_rand_state {* the entropy pool having similar initial state across largely * identical devices. */ -void add_device_randomness (const void *buf,unsigned int size) +void add_device_randomness (const void *buf,size_t size) {unsigned long time =random_get_entropy () ^ jiffies;unsigned long flags;
@@ -811,7 +793,7 @@ static struct timer_rand_state input_tim* keyboard scan codes, and 256 upwards for interrupts. * */ -static void add_timer_randomness (struct timer_rand_state *state,unsigned num) +static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) {struct {long jiffies;
@@ -855,7 +837,7 @@ static void add_timer_randomness(struct* Round down by 1 bit on general principles, * and limit entropy estimate to 12 bits. */ -credit_entropy_bits (min_t (int,fls (delta >>1 ),11 )); + credit_entropy_bits(min_t(unsigned int, fls(delta >> 1), 11)); } void add_input_randomness(unsigned int type, unsigned int code,
@@ -936,8 +918,8 @@ void add_interrupt_randomness(int irq)add_interrupt_bench (cycles);if (unlikely (crng_init ==0 )) { -if ((fast_pool->count >=64 ) && -crng_fast_load ((u8 *)fast_pool->pool,sizeof (fast_pool->pool)) >0 ) { +if (fast_pool->count >=64 && +crng_fast_load (fast_pool->pool,sizeof (fast_pool->pool)) >0 ) { fast_pool->count =0 ; fast_pool->last = now;if (spin_trylock (&input_pool.lock)) {
@@ -955,7 +937,7 @@ void add_interrupt_randomness(int irq)return ; fast_pool->last = now; -__mix_pool_bytes (&fast_pool->pool,sizeof (fast_pool->pool)); +_mix_pool_bytes (&fast_pool->pool,sizeof (fast_pool->pool));spin_unlock (&input_pool.lock); fast_pool->count =0 ;
@@ -1064,18 +1046,18 @@ static void _warn_unseeded_randomness(co* wait_for_random_bytes() should be called and return 0 at least once * at any point prior. */ -static void _get_random_bytes (void *buf,int nbytes) +static void _get_random_bytes (void *buf,size_t nbytes) {u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)];u8 tmp[CHACHA20_BLOCK_SIZE ]; -ssize_t len; +size_t len;trace_get_random_bytes (nbytes, _RET_IP_);if (!nbytes)return ; - len =min_t (ssize_t,32 , nbytes); + len =min_t (size_t,32 , nbytes);crng_make_state (chacha_state, buf, len); nbytes -= len; buf += len;
@@ -1098,7 +1080,7 @@ static void _get_random_bytes(void *buf,memzero_explicit (chacha_state,sizeof (chacha_state)); } -void get_random_bytes (void *buf,int nbytes) +void get_random_bytes (void *buf,size_t nbytes) {static void *previous;
@@ -1259,25 +1241,19 @@ EXPORT_SYMBOL(del_random_ready_callback)/* * This function will use the architecture-specific hardware random -* number generator if it is available. The arch-specific hw RNG will -* almost certainly be faster than what we can do in software, but it -* is impossible to verify that it is implemented securely (as -* opposed, to, say, the AES encryption of a sequence number using a -* key known by the NSA). So it's useful if we need the speed, but -* only if we're willing to trust the hardware manufacturer not to -* have put in a back door. -* -* Return number of bytes filled in. +* number generator if it is available. It is not recommended for +* use. Use get_random_bytes() instead. It returns the number of +* bytes filled in. */ -int __must_check get_random_bytes_arch (void *buf,int nbytes) +size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes) { -int left = nbytes; +size_t left = nbytes;u8 *p = buf;trace_get_random_bytes_arch (left, _RET_IP_);while (left) {unsigned long v; -int chunk =min_t (int, left,sizeof (unsigned long )); +size_t chunk =min_t (size_t, left,sizeof (unsigned long ));if (!arch_get_random_long (&v))break ;
@@ -1310,12 +1286,12 @@ early_param("random.trust_cpu", parse_tr*/ int __init rand_initialize (void ) { -int i; +size_t i;ktime_t now =ktime_get_real ();bool arch_init = true;unsigned long rv; -for (i =BLAKE2S_BLOCK_SIZE ; i >0 ; i -=sizeof (rv)) { +for (i =0 ; i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) {if (!arch_get_random_seed_long_early (&rv) && !arch_get_random_long_early (&rv)) { rv =random_get_entropy ();
@@ -1364,7 +1340,7 @@ static ssize_t urandom_read_nowarn(struc nbytes =min_t (size_t, nbytes,INT_MAX >>6 ); ret =get_random_bytes_user (buf, nbytes); -trace_urandom_read (8 * nbytes,0 , input_pool.entropy_count); +trace_urandom_read (nbytes, input_pool.entropy_count);return ret; }
@@ -1408,19 +1384,18 @@ static unsigned int random_poll(struct freturn mask; } -static int write_pool (const char __user *buffer,size_t count) +static int write_pool (const char __user *ubuf,size_t count) { -size_t bytes; -u8 buf[BLAKE2S_BLOCK_SIZE ]; -const char __user *p = buffer; - -while (count >0 ) { - bytes =min (count,sizeof (buf)); -if (copy_from_user (buf, p, bytes)) +size_t len; +u8 block[BLAKE2S_BLOCK_SIZE ]; + +while (count) { + len =min (count,sizeof (block)); +if (copy_from_user (block, ubuf, len))return -EFAULT ; - count -= bytes; - p += bytes; -mix_pool_bytes (buf, bytes); + count -= len; + ubuf += len; +mix_pool_bytes (block, len);cond_resched (); }
@@ -1430,7 +1405,7 @@ static int write_pool(const char __userstatic ssize_t random_write (struct file *file,const char __user *buffer,size_t count,loff_t *ppos) { -size_t ret; +int ret; ret =write_pool (buffer, count);if (ret)
@@ -1524,8 +1499,6 @@ const struct file_operations urandom_fop SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int, flags) { -int ret; -if (flags & ~(GRND_NONBLOCK |GRND_RANDOM |GRND_INSECURE ))return -EINVAL ;
@@ -1540,6 +1513,8 @@ SYSCALL_DEFINE3(getrandom, char __user * count =INT_MAX ;if (!(flags &GRND_INSECURE ) && !crng_ready ()) { +int ret; +if (flags &GRND_NONBLOCK )return -EAGAIN ; ret =wait_for_random_bytes ();
@@ -1798,7 +1773,7 @@ unsigned long randomize_page(unsigned lo* Those devices may produce endless random bits and will be throttled * when our pool is full. */ -void add_hwgenerator_randomness (const char *buffer,size_t count, +void add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy) {if (unlikely (crng_init ==0 )) {
@@ -1829,7 +1804,7 @@ EXPORT_SYMBOL_GPL(add_hwgenerator_random* it would be regarded as device data. * The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER. */ -void add_bootloader_randomness (const void *buf,unsigned int size) +void add_bootloader_randomness (const void *buf,size_t size) {if (IS_ENABLED (CONFIG_RANDOM_TRUST_BOOTLOADER ))add_hwgenerator_randomness (buf, size, size *8 );
include/linux/hw_random.h +1 -1
@@ -61,6 +61,6 @@ extern int devm_hwrng_register(struct deextern void hwrng_unregister (struct hwrng *rng);extern void devm_hwrng_unregister (struct device *dve,struct hwrng *rng);/** Feed random bits into the pool. */ -extern void add_hwgenerator_randomness (const char *buffer,size_t count,size_t entropy); +extern void add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy);#endif /* LINUX_HWRANDOM_H_ */
include/linux/random.h +5 -5
@@ -19,8 +19,8 @@ struct random_ready_callback {struct module *owner; }; -extern void add_device_randomness (const void *,unsigned int ); -extern void add_bootloader_randomness (const void *,unsigned int ); +extern void add_device_randomness (const void *,size_t ); +extern void add_bootloader_randomness (const void *,size_t );#if defined(LATENT_ENTROPY_PLUGIN ) && !defined(__CHECKER__)static inline void add_latent_entropy (void )
@@ -36,13 +36,13 @@ extern void add_input_randomness(unsigne unsigned int value) __latent_entropy; extern void add_interrupt_randomness(int irq) __latent_entropy; -extern void get_random_bytes (void *buf,int nbytes); +extern void get_random_bytes (void *buf,size_t nbytes);extern int wait_for_random_bytes (void );extern int __init rand_initialize (void );extern bool rng_is_initialized (void );extern int add_random_ready_callback (struct random_ready_callback *rdy);extern void del_random_ready_callback (struct random_ready_callback *rdy); -extern int __must_check get_random_bytes_arch (void *buf,int nbytes); +extern size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes);#ifndef MODULE extern const struct file_operations random_fops, urandom_fops;
@@ -65,7 +65,7 @@ static inline unsigned long get_random_l/* Calls wait_for_random_bytes() and then calls get_random_bytes(buf, nbytes). * Returns the result of the call to wait_for_random_bytes. */ -static inline int get_random_bytes_wait (void *buf,int nbytes) +static inline int get_random_bytes_wait (void *buf,size_t nbytes) {int ret =wait_for_random_bytes ();get_random_bytes (buf, nbytes);
include/trace/events/random.h +38 -41
211 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 124/264 random: remove outdated INT_MAX >> 6 check in urandom_read()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 434537ae54ad37e93555de21b6ac8133d6d773a9 upstream.
In 79a8468747c5 ("random: check for increase of entropy_count because of signed conversion"), a number of checks were added around what values were passed to account(), because account() was doing fancy fixed point fractional arithmetic, and a user had some ability to pass large values directly into it. One of things in that commit was limiting those values to INT_MAX >> 6. The first >> 3 was for bytes to bits, and the next >> 3 was for bits to 1/8 fractional bits.
However, for several years now, urandom reads no longer touch entropy accounting, and so this check serves no purpose. The current flow is:
urandom_read_nowarn()-->get_random_bytes_user()-->chacha20_block()
Of course, we don't want that size_t to be truncated when adding it into the ssize_t. But we arrive at urandom_read_nowarn() in the first place either via ordinary fops, which limits reads to MAX_RW_COUNT, or via getrandom() which limits reads to INT_MAX.
--- drivers/char/random.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/char/random.c +1 -2
@@ -1336,9 +1336,8 @@ void rand_initialize_disk(struct gendiskstatic ssize_t urandom_read_nowarn (struct file *file,char __user *buf,size_t nbytes,loff_t *ppos) { -int ret; +ssize_t ret; - nbytes =min_t (size_t, nbytes,INT_MAX >>6 ); ret =get_random_bytes_user (buf, nbytes);trace_urandom_read (nbytes, input_pool.entropy_count);return ret;
Greg Kroah-Hartman
maintainerPATCH 125/264 random: zero buffer after reading entropy from userspace
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 7b5164fb1279bf0251371848e40bae646b59b3a8 upstream.
This buffer may contain entropic data that shouldn't stick around longer than needed, so zero out the temporary buffer at the end of write_pool().
--- drivers/char/random.c | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-)
drivers/char/random.c +14 -6
@@ -552,6 +552,7 @@ static void crng_reseed(void)int entropy_count;unsigned long next_gen;u8 key[CHACHA20_KEY_SIZE ]; +bool finalize_init = false;/* * First we make sure we have POOL_MIN_BITS of entropy in the pool,
@@ -579,12 +580,14 @@ static void crng_reseed(void) ++next_gen;WRITE_ONCE (base_crng.generation, next_gen);WRITE_ONCE (base_crng.birth, jiffies); -spin_unlock_irqrestore (&base_crng.lock, flags); -memzero_explicit (key,sizeof (key)); -if (crng_init <2 ) {invalidate_batched_entropy (); crng_init =2 ; + finalize_init = true; + } +spin_unlock_irqrestore (&base_crng.lock, flags); +memzero_explicit (key,sizeof (key)); +if (finalize_init) {process_random_ready_list ();wake_up_interruptible (&crng_init_wait);kill_fasync (&fasync,SIGIO ,POLL_IN );
@@ -1386,19 +1389,24 @@ static unsigned int random_poll(struct fstatic int write_pool (const char __user *ubuf,size_t count) {size_t len; +int ret =0 ;u8 block[BLAKE2S_BLOCK_SIZE ];while (count) { len =min (count,sizeof (block)); -if (copy_from_user (block, ubuf, len)) -return -EFAULT ; +if (copy_from_user (block, ubuf, len)) { + ret = -EFAULT ; + goto out; + } count -= len; ubuf += len;mix_pool_bytes (block, len);cond_resched (); } -return 0 ; +out: +memzero_explicit (block,sizeof (block)); +return ret; } static ssize_t random_write(struct file *file, const char __user *buffer,
Greg Kroah-Hartman
maintainerPATCH 126/264 random: tie batched entropy generation to base_crng generation
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 0791e8b655cc373718f0f58800fdc625a3447ac5 upstream.
Now that we have an explicit base_crng generation counter, we don't need a separate one for batched entropy. Rather, we can just move the generation forward every time we change crng_init state or update the base_crng key.
--- drivers/char/random.c | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-)
drivers/char/random.c +8 -21
@@ -429,8 +429,6 @@ static DEFINE_PER_CPU(struct crng, crngsstatic DECLARE_WAIT_QUEUE_HEAD (crng_init_wait); -static void invalidate_batched_entropy (void ); -/* * crng_fast_load() can be called by code in the interrupt service * path. So we can't afford to dilly-dally. Returns the number of
@@ -453,7 +451,7 @@ static size_t crng_fast_load(const void src++; crng_init_cnt++; len--; ret++; }if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { -invalidate_batched_entropy (); + ++base_crng.generation; crng_init =1 ; }spin_unlock_irqrestore (&base_crng.lock, flags);
@@ -581,7 +579,6 @@ static void crng_reseed(void)WRITE_ONCE (base_crng.generation, next_gen);WRITE_ONCE (base_crng.birth, jiffies);if (crng_init <2 ) { -invalidate_batched_entropy (); crng_init =2 ; finalize_init = true; }
@@ -1306,8 +1303,9 @@ int __init rand_initialize(void)mix_pool_bytes (utsname (),sizeof (*(utsname ())));extract_entropy (base_crng.key,sizeof (base_crng.key)); + ++base_crng.generation; +if (arch_init && trust_cpu && crng_init <2 ) { -invalidate_batched_entropy (); crng_init =2 ;pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); }
@@ -1645,8 +1643,6 @@ struct ctl_table random_table[] = { };#endif /* CONFIG_SYSCTL */ -static atomic_t batch_generation =ATOMIC_INIT (0 ); - struct batched_entropy { union {/*
@@ -1659,8 +1655,8 @@ struct batched_entropy {u64 entropy_u64[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u64))];u32 entropy_u32[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u32))]; }; +unsigned long generation;unsigned int position; -int generation; };/*
@@ -1679,14 +1675,14 @@ u64 get_random_u64(void)unsigned long flags;struct batched_entropy *batch;static void *previous; -int next_gen; +unsigned long next_gen;warn_unseeded_randomness (&previous);local_irq_save (flags); batch =raw_cpu_ptr (&batched_entropy_u64); - next_gen =atomic_read (&batch_generation); + next_gen =READ_ONCE (base_crng.generation);if (batch->position >=ARRAY_SIZE (batch->entropy_u64) || next_gen != batch->generation) {_get_random_bytes (batch->entropy_u64,sizeof (batch->entropy_u64));
@@ -1712,14 +1708,14 @@ u32 get_random_u32(void)unsigned long flags;struct batched_entropy *batch;static void *previous; -int next_gen; +unsigned long next_gen;warn_unseeded_randomness (&previous);local_irq_save (flags); batch =raw_cpu_ptr (&batched_entropy_u32); - next_gen =atomic_read (&batch_generation); + next_gen =READ_ONCE (base_crng.generation);if (batch->position >=ARRAY_SIZE (batch->entropy_u32) || next_gen != batch->generation) {_get_random_bytes (batch->entropy_u32,sizeof (batch->entropy_u32));
@@ -1735,15 +1731,6 @@ u32 get_random_u32(void) }EXPORT_SYMBOL (get_random_u32); -/* It's important to invalidate all potential batched entropy that might -* be stored before the crng is initialized, which we can do lazily by -* bumping the generation counter. -*/ -static void invalidate_batched_entropy (void ) -{ -atomic_inc (&batch_generation); -} -/** * randomize_page - Generate a random, page aligned address * @start: The smallest acceptable address the caller will take.
Greg Kroah-Hartman
maintainerPATCH 127/264 random: remove ifdefd out interrupt bench
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 95e6060c20a7f5db60163274c5222a725ac118f9 upstream.
With tools like kbench9000 giving more finegrained responses, and this basically never having been used ever since it was initially added, let's just get rid of this. There *is* still work to be done on the interrupt handler, but this really isn't the way it's being developed.
--- Documentation/sysctl/kernel.txt | 9 --------- drivers/char/random.c | 40 ---------------------------------------- 2 files changed, 49 deletions(-)
Documentation/sysctl/kernel.txt +0 -9
@@ -808,15 +808,6 @@ This is a directory, with the following are woken up. This file is writable for compatibility purposes, but writing to it has no effect on any RNG behavior. -If ``drivers/char/random.c`` is built with ``ADD_INTERRUPT_BENCH`` -defined, these additional entries are present: - -* ``add_interrupt_avg_cycles``: the average number of cycles between - interrupts used to feed the pool; - -* ``add_interrupt_avg_deviation``: the standard deviation seen on the - number of cycles between interrupts used to feed the pool. - randomize_va_space ==================
drivers/char/random.c +0 -40
@@ -241,8 +241,6 @@#define CREATE_TRACE_POINTS #include <trace/events/random.h> -/* #define ADD_INTERRUPT_BENCH */ -enum {POOL_BITS =BLAKE2S_HASH_SIZE *8 ,POOL_MIN_BITS =POOL_BITS /* No point in settling for less. */
@@ -858,27 +856,6 @@ EXPORT_SYMBOL_GPL(add_input_randomness); static DEFINE_PER_CPU(struct fast_pool, irq_randomness); -#ifdef ADD_INTERRUPT_BENCH -static unsigned long avg_cycles, avg_deviation; - -#define AVG_SHIFT 8/* Exponential average factor k=1/256 */ -#define FIXED_1_2 (1 << (AVG_SHIFT - 1)) - -static void add_interrupt_bench (cycles_t start) -{ -long delta =random_get_entropy () - start; - -/* Use a weighted moving average */ - delta = delta - ((avg_cycles +FIXED_1_2 ) >>AVG_SHIFT ); - avg_cycles += delta; -/* And average deviation */ - delta =abs (delta) - ((avg_deviation +FIXED_1_2 ) >>AVG_SHIFT ); - avg_deviation += delta; -} -#else -#define add_interrupt_bench (x) -#endif -static u32 get_reg (struct fast_pool *f,struct pt_regs *regs) {u32 *ptr = (u32 *)regs;
@@ -915,7 +892,6 @@ void add_interrupt_randomness(int irq) (sizeof (ip) >4 ) ? ip >>32 :get_reg (fast_pool, regs);fast_mix (fast_pool); -add_interrupt_bench (cycles);if (unlikely (crng_init ==0 )) { if (fast_pool->count >= 64 &&
@@ -1623,22 +1599,6 @@ struct ctl_table random_table[] = { .mode = 0444, .proc_handler = proc_do_uuid, }, -#ifdef ADD_INTERRUPT_BENCH - { - .procname = "add_interrupt_avg_cycles", - .data = &avg_cycles, - .maxlen = sizeof(avg_cycles), - .mode = 0444, - .proc_handler = proc_doulongvec_minmax, - }, - { - .procname = "add_interrupt_avg_deviation", - .data = &avg_deviation, - .maxlen = sizeof(avg_deviation), - .mode = 0444, - .proc_handler = proc_doulongvec_minmax, - }, -#endif { } };#endif /* CONFIG_SYSCTL */
Greg Kroah-Hartman
maintainerPATCH 128/264 random: remove unused tracepoints
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 14c174633f349cb41ea90c2c0aaddac157012f74 upstream.
These explicit tracepoints aren't really used and show sign of aging. It's work to keep these up to date, and before I attempted to keep them up to date, they weren't up to date, which indicates that they're not really used. These days there are better ways of introspecting anyway.
--- drivers/char/random.c | 30 ------ include/trace/events/random.h | 194 ------------------------------------------ lib/random32.c | 2 3 files changed, 5 insertions(+), 221 deletions(-) delete mode 100644 include/trace/events/random.h
drivers/char/random.c +3 -27
@@ -238,9 +238,6 @@#include <asm/irq_regs.h> #include <asm/io.h> -#define CREATE_TRACE_POINTS -#include <trace/events/random.h> -enum {POOL_BITS =BLAKE2S_HASH_SIZE *8 ,POOL_MIN_BITS =POOL_BITS /* No point in settling for less. */
@@ -316,7 +313,6 @@ static void mix_pool_bytes(const void *i {unsigned long flags; -trace_mix_pool_bytes (nbytes, _RET_IP_);spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (in, nbytes);spin_unlock_irqrestore (&input_pool.lock, flags);
@@ -390,8 +386,6 @@ static void credit_entropy_bits(size_t n entropy_count = min_t(unsigned int, POOL_BITS, orig + add); }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); -trace_credit_entropy_bits (nbits, entropy_count, _RET_IP_); -if (crng_init <2 && entropy_count >=POOL_MIN_BITS )crng_reseed (); }
@@ -771,7 +765,6 @@ void add_device_randomness(const void *bif (!crng_ready () && size)crng_slow_load (buf, size); -trace_add_device_randomness (size, _RET_IP_);spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (buf, size);_mix_pool_bytes (&time,sizeof (time));
@@ -850,7 +843,6 @@ void add_input_randomness(unsigned int t last_value = value;add_timer_randomness (&input_timer_state, (type <<4 ) ^ code ^ (code >>4 ) ^ value); -trace_add_input_randomness (input_pool.entropy_count); }EXPORT_SYMBOL_GPL (add_input_randomness);
@@ -930,7 +922,6 @@ void add_disk_randomness(struct gendiskreturn ;/* first major is 1, so we get >= 0x200 here */ add_timer_randomness(disk->random, 0x100 + disk_devt(disk)); - trace_add_disk_randomness(disk_devt(disk), input_pool.entropy_count); }EXPORT_SYMBOL_GPL (add_disk_randomness);#endif
@@ -955,8 +946,6 @@ static void extract_entropy(void *buf, s } block;size_t i; -trace_extract_entropy (nbytes, input_pool.entropy_count); -for (i =0 ; i <ARRAY_SIZE (block.rdseed); ++i) {if (!arch_get_random_seed_long (&block.rdseed[i]) && !arch_get_random_long (&block.rdseed[i]))
@@ -1028,8 +1017,6 @@ static void _get_random_bytes(void *buf,u8 tmp[CHACHA20_BLOCK_SIZE ];size_t len; -trace_get_random_bytes (nbytes, _RET_IP_); -if (!nbytes)return ;
@@ -1226,7 +1213,6 @@ size_t __must_check get_random_bytes_arcsize_t left = nbytes;u8 *p = buf; -trace_get_random_bytes_arch (left, _RET_IP_);while (left) {unsigned long v;size_t chunk =min_t (size_t, left,sizeof (unsigned long ));
@@ -1310,16 +1296,6 @@ void rand_initialize_disk(struct gendisk }#endif -static ssize_t urandom_read_nowarn (struct file *file,char __user *buf, -size_t nbytes,loff_t *ppos) -{ -ssize_t ret; - - ret =get_random_bytes_user (buf, nbytes); -trace_urandom_read (nbytes, input_pool.entropy_count); -return ret; -} -static ssize_t urandom_read (struct file *file,char __user *buf,size_t nbytes,loff_t *ppos) {
@@ -1332,7 +1308,7 @@ static ssize_t urandom_read(struct file current->comm, nbytes); } -return urandom_read_nowarn (file, buf, nbytes, ppos); +return get_random_bytes_user (buf, nbytes); } static ssize_t random_read(struct file *file, char __user *buf, size_t nbytes,
@@ -1343,7 +1319,7 @@ static ssize_t random_read(struct file * ret =wait_for_random_bytes ();if (ret !=0 )return ret; -return urandom_read_nowarn (file, buf, nbytes, ppos); +return get_random_bytes_user (buf, nbytes); }static unsigned int random_poll (struct file *file,poll_table *wait)
@@ -1502,7 +1478,7 @@ SYSCALL_DEFINE3(getrandom, char __user *if (unlikely (ret))return ret; } -return urandom_read_nowarn (NULL , buf, count,NULL ); +return get_random_bytes_user (buf, count); }/********************************************************************
include/trace/events/random.h deleted +0 -194
194 lines not on this page · raw message
lib/random32.c +2 -0
@@ -37,6 +37,8 @@#include <linux/jiffies.h> #include <linux/random.h> #include <linux/sched.h> +#include <linux/bitops.h> +#include <linux/slab.h> #include <asm/unaligned.h> /**
Greg Kroah-Hartman
maintainerPATCH 129/264 random: add proper SPDX header
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a07fdae346c35c6ba286af1c88e0effcfa330bf9 upstream.
Convert the current license into the SPDX notation of "(GPL-2.0 OR BSD-3-Clause)". This infers GPL-2.0 from the text "ALTERNATIVELY, this product may be distributed under the terms of the GNU General Public License, in which case the provisions of the GPL are required INSTEAD OF the above restrictions" and it infers BSD-3-Clause from the verbatim BSD 3 clause license in the file.
--- drivers/char/random.c | 37 +------------------------------------ 1 file changed, 1 insertion(+), 36 deletions(-)
drivers/char/random.c +1 -36
@@ -1,44 +1,9 @@ +// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) /* -* random.c -- A strong random number generator -* * Copyright (C) 2017-2022 Jason A. Donenfeld <[email protected]>. All Rights Reserved. -* * Copyright Matt Mackall <[email protected]>, 2003, 2004, 2005 -* * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. 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, and the entire permission notice in its entirety, -* including the disclaimer of warranties. -* 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. -* 3. The name of the author may not be used to endorse or promote -* products derived from this software without specific prior -* written permission. -* -* ALTERNATIVELY, this product may be distributed under the terms of -* the GNU General Public License, in which case the provisions of the GPL are -* required INSTEAD OF the above restrictions. (This clause is -* necessary due to a potential bad interaction between the GPL and -* the restrictions contained in a BSD-style copyright.) -* -* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED -* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF -* WHICH ARE HEREBY 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 NOT ADVISED OF THE POSSIBILITY OF SUCH -* DAMAGE. */ /*
Greg Kroah-Hartman
maintainerPATCH 130/264 random: deobfuscate irq u32/u64 contributions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit b2f408fe403800c91a49f6589d95b6759ce1b30b upstream.
In the irq handler, we fill out 16 bytes differently on 32-bit and 64-bit platforms, and for 32-bit vs 64-bit cycle counters, which doesn't always correspond with the bitness of the platform. Whether or not you like this strangeness, it is a matter of fact. But it might not be a fact you well realized until now, because the code that loaded the irq info into 4 32-bit words was quite confusing. Instead, this commit makes everything explicit by having separate (compile-time) branches for 32-bit and 64-bit types.
--- drivers/char/random.c | 49 ++++++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 21 deletions(-)
drivers/char/random.c +28 -21
@@ -284,7 +284,10 @@ static void mix_pool_bytes(const void *i }struct fast_pool { -u32 pool[4 ]; +union { +u32 pool32[4 ]; +u64 pool64[2 ]; + };unsigned long last;u16 reg_idx;u8 count;
@@ -295,10 +298,10 @@ struct fast_pool {* collector. It's hardcoded for an 128 bit pool and assumes that any * locks that might be needed are taken by the caller. */ -static void fast_mix (struct fast_pool *f) +static void fast_mix (u32 pool[4 ]) { -u32 a = f->pool[0 ], b = f->pool[1 ]; -u32 c = f->pool[2 ], d = f->pool[3 ]; +u32 a = pool[0 ], b = pool[1 ]; +u32 c = pool[2 ], d = pool[3 ]; a += b; c += d; b =rol32 (b,6 ); d =rol32 (d,27 );
@@ -316,9 +319,8 @@ static void fast_mix(struct fast_pool *f b =rol32 (b,16 ); d =rol32 (d,14 ); d ^= a; b ^= c; - f->pool[0 ] = a; f->pool[1 ] = b; - f->pool[2 ] = c; f->pool[3 ] = d; - f->count++; + pool[0 ] = a; pool[1 ] = b; + pool[2 ] = c; pool[3 ] = d; }static void process_random_ready_list (void )
@@ -834,29 +836,34 @@ void add_interrupt_randomness(int irq)struct pt_regs *regs =get_irq_regs ();unsigned long now = jiffies;cycles_t cycles =random_get_entropy (); -u32 c_high, j_high; -u64 ip;if (cycles ==0 ) cycles =get_reg (fast_pool, regs); - c_high = (sizeof (cycles) >4 ) ? cycles >>32 :0 ; - j_high = (sizeof (now) >4 ) ? now >>32 :0 ; - fast_pool->pool[0 ] ^= cycles ^ j_high ^ irq; - fast_pool->pool[1 ] ^= now ^ c_high; - ip = regs ?instruction_pointer (regs) : _RET_IP_; - fast_pool->pool[2 ] ^= ip; - fast_pool->pool[3 ] ^= - (sizeof (ip) >4 ) ? ip >>32 :get_reg (fast_pool, regs); -fast_mix (fast_pool); +if (sizeof (cycles) ==8 ) + fast_pool->pool64[0 ] ^= cycles ^rol64 (now,32 ) ^ irq; +else { + fast_pool->pool32[0 ] ^= cycles ^ irq; + fast_pool->pool32[1 ] ^= now; + } + +if (sizeof (unsigned long ) ==8 ) + fast_pool->pool64[1 ] ^= regs ?instruction_pointer (regs) : _RET_IP_; +else { + fast_pool->pool32[2 ] ^= regs ?instruction_pointer (regs) : _RET_IP_; + fast_pool->pool32[3 ] ^=get_reg (fast_pool, regs); + } + +fast_mix (fast_pool->pool32); + ++fast_pool->count;if (unlikely (crng_init ==0 )) {if (fast_pool->count >=64 && -crng_fast_load (fast_pool->pool,sizeof (fast_pool->pool)) >0 ) { +crng_fast_load (fast_pool->pool32,sizeof (fast_pool->pool32)) >0 ) { fast_pool->count =0 ; fast_pool->last = now;if (spin_trylock (&input_pool.lock)) { -_mix_pool_bytes (&fast_pool->pool,sizeof (fast_pool->pool)); +_mix_pool_bytes (&fast_pool->pool32,sizeof (fast_pool->pool32));spin_unlock (&input_pool.lock); } }
@@ -870,7 +877,7 @@ void add_interrupt_randomness(int irq)return ; fast_pool->last = now; -_mix_pool_bytes (&fast_pool->pool,sizeof (fast_pool->pool)); +_mix_pool_bytes (&fast_pool->pool32,sizeof (fast_pool->pool32));spin_unlock (&input_pool.lock); fast_pool->count =0 ;
Greg Kroah-Hartman
maintainerPATCH 131/264 random: introduce drain_entropy() helper to declutter crng_reseed()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 246c03dd899164d0186b6d685d6387f228c28d93 upstream.
In preparation for separating responsibilities, break out the entropy count management part of crng_reseed() into its own function.
No functional changes.
--- drivers/char/random.c | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-)
drivers/char/random.c +23 -13
@@ -261,6 +261,7 @@ static struct { };static void extract_entropy (void *buf,size_t nbytes); +static bool drain_entropy (void *buf,size_t nbytes);static void crng_reseed (void );
@@ -506,23 +507,13 @@ static void crng_slow_load(const void *cstatic void crng_reseed (void ) {unsigned long flags; -int entropy_count;unsigned long next_gen;u8 key[CHACHA20_KEY_SIZE ];bool finalize_init = false; -/* -* First we make sure we have POOL_MIN_BITS of entropy in the pool, -* and then we drain all of it. Only then can we extract a new key. -*/ -do { - entropy_count =READ_ONCE (input_pool.entropy_count); -if (entropy_count <POOL_MIN_BITS ) -return ; - }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); -extract_entropy (key,sizeof (key)); -wake_up_interruptible (&random_write_wait); -kill_fasync (&fasync,SIGIO ,POLL_OUT ); +/* Only reseed if we can, to prevent brute forcing a small amount of new bits. */ +if (!drain_entropy (key,sizeof (key))) +return ;/* * We copy the new key into the base_crng, overwriting the old one,
@@ -950,6 +941,25 @@ static void extract_entropy(void *buf, smemzero_explicit (&block,sizeof (block)); } +/* +* First we make sure we have POOL_MIN_BITS of entropy in the pool, and then we +* set the entropy count to zero (but don't actually touch any data). Only then +* can we extract a new key with extract_entropy(). +*/ +static bool drain_entropy (void *buf,size_t nbytes) +{ +unsigned int entropy_count; +do { + entropy_count =READ_ONCE (input_pool.entropy_count); +if (entropy_count <POOL_MIN_BITS ) +return false; + }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); +extract_entropy (buf, nbytes); +wake_up_interruptible (&random_write_wait); +kill_fasync (&fasync,SIGIO ,POLL_OUT ); +return true; +} +#define warn_unseeded_randomness (previous) \ _warn_unseeded_randomness(__func__, (void *)_RET_IP_, (previous))
Greg Kroah-Hartman
maintainerPATCH 132/264 random: remove useless header comment
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 6071a6c0fba2d747742cadcbb3ba26ed756ed73b upstream.
This really adds nothing at all useful.
--- include/linux/random.h | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-)
include/linux/random.h +2 -5
@@ -1,8 +1,5 @@ -/* -* include/linux/random.h -* -* Include file for the random number generator. -*/ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_RANDOM_H#define _LINUX_RANDOM_H
Greg Kroah-Hartman
maintainerPATCH 133/264 random: remove whitespace and reorder includes
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 87e7d5abad0cbc9312dea7f889a57d294c1a5fcc upstream.
This is purely cosmetic. Future work involves figuring out which of these headers we need and which we don't.
--- drivers/char/random.c | 1 - 1 file changed, 1 deletion(-)
drivers/char/random.c +0 -1
@@ -196,7 +196,6 @@#include <linux/uuid.h> #include <crypto/chacha20.h> #include <crypto/blake2s.h> -#include <asm/processor.h> #include <asm/uaccess.h> #include <asm/irq.h>
Greg Kroah-Hartman
maintainerPATCH 134/264 random: group initialization wait functions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 5f1bb112006b104b3e2a1e1b39bbb9b2617581e6 upstream.
This pulls all of the readiness waiting-focused functions into the first labeled section.
No functional changes.
--- drivers/char/random.c | 1066 ++++++++++++++++++++++++-------------------------- 1 file changed, 527 insertions(+), 539 deletions(-)
drivers/char/random.c +527 -539
@@ -202,126 +202,144 @@#include <asm/irq_regs.h> #include <asm/io.h> -enum { -POOL_BITS =BLAKE2S_HASH_SIZE *8 , -POOL_MIN_BITS =POOL_BITS /* No point in settling for less. */ -}; - -/* -* Static global variables -*/ -static DECLARE_WAIT_QUEUE_HEAD (random_write_wait); -static struct fasync_struct *fasync; - -static DEFINE_SPINLOCK (random_ready_list_lock); -static LIST_HEAD (random_ready_list); +/********************************************************************* +* +* 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 = 0 --> Uninitialized * 1 --> Initialized * 2 --> Initialized from input_pool * -* crng_init is protected by primary_crng->lock, and only increases +* crng_init is protected by base_crng->lock, and only increases * its value (from 0->1->2). */ static int crng_init =0 ;#define crng_ready () (likely(crng_init > 1)) -static int crng_init_cnt =0 ; -static void process_random_ready_list (void ); -static void _get_random_bytes (void *buf,size_t nbytes); +/* Various types of waiters for crng_init->2 transition. */ +static DECLARE_WAIT_QUEUE_HEAD (crng_init_wait); +static struct fasync_struct *fasync; +static DEFINE_SPINLOCK (random_ready_list_lock); +static LIST_HEAD (random_ready_list); +/* Control how we warn userspace. */ static struct ratelimit_state unseeded_warning =RATELIMIT_STATE_INIT ("warn_unseeded_randomness" ,HZ ,3 );static struct ratelimit_state urandom_warning =RATELIMIT_STATE_INIT ("warn_urandom_randomness" ,HZ ,3 ); -static int ratelimit_disable__read_mostly ; -module_param_named (ratelimit_disable, ratelimit_disable, int,0644 );MODULE_PARM_DESC (ratelimit_disable,"Disable random ratelimit suppression" ); -/********************************************************************** -* -* OS independent entropy store. Here are the functions which handle -* storing entropy in an entropy pool. +/* +* 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_{u32, +* ,u64,int,long} family of functions. * -**********************************************************************/ - -static struct { -struct blake2s_state hash; -spinlock_t lock; -unsigned int entropy_count; -} input_pool = { - .hash.h = {BLAKE2S_IV0 ^ (0x01010000 |BLAKE2S_HASH_SIZE ), -BLAKE2S_IV1 ,BLAKE2S_IV2 ,BLAKE2S_IV3 ,BLAKE2S_IV4 , -BLAKE2S_IV5 ,BLAKE2S_IV6 ,BLAKE2S_IV7 }, - .hash.outlen =BLAKE2S_HASH_SIZE , - .lock =__SPIN_LOCK_UNLOCKED (input_pool.lock), -}; - -static void extract_entropy (void *buf,size_t nbytes); -static bool drain_entropy (void *buf,size_t nbytes); +* 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 crng_reseed (void ); +/* Used by wait_for_random_bytes(), and considered an entropy collector, below. */ +static void try_to_generate_entropy (void );/* -* This function adds bytes into the entropy "pool". It does not -* update the entropy estimate. The caller should call -* credit_entropy_bits if this is appropriate. +* 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_{u32,u64,int,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. */ -static void _mix_pool_bytes (const void *in,size_t nbytes) +int wait_for_random_bytes (void ) { -blake2s_update (&input_pool.hash, in, nbytes); -} +if (likely (crng_ready ())) +return 0 ; -static void mix_pool_bytes (const void *in,size_t nbytes) -{ -unsigned long flags; +do { +int ret; + ret =wait_event_interruptible_timeout (crng_init_wait,crng_ready (),HZ ); +if (ret) +return ret >0 ?0 : ret; -spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (in, nbytes); -spin_unlock_irqrestore (&input_pool.lock, flags); -} +try_to_generate_entropy (); + }while (!crng_ready ()); -struct fast_pool { -union { -u32 pool32[4 ]; -u64 pool64[2 ]; - }; -unsigned long last; -u16 reg_idx; -u8 count; -}; +return 0 ; +} +EXPORT_SYMBOL (wait_for_random_bytes);/* -* This is a fast mixing routine used by the interrupt randomness -* collector. It's hardcoded for an 128 bit pool and assumes that any -* locks that might be needed are taken by the caller. +* Add a callback function that will be invoked when the input +* pool is initialised. +* +* returns: 0 if callback is successfully added +* -EALREADY if pool is already initialised (callback not called) +* -ENOENT if module for callback is not alive */ -static void fast_mix (u32 pool[4 ]) +int add_random_ready_callback (struct random_ready_callback *rdy) { -u32 a = pool[0 ], b = pool[1 ]; -u32 c = pool[2 ], d = pool[3 ]; +struct module *owner; +unsigned long flags; +int err = -EALREADY ; - a += b; c += d; - b =rol32 (b,6 ); d =rol32 (d,27 ); - d ^= a; b ^= c; +if (crng_ready ()) +return err; - a += b; c += d; - b =rol32 (b,16 ); d =rol32 (d,14 ); - d ^= a; b ^= c; + owner = rdy->owner; +if (!try_module_get (owner)) +return -ENOENT ; - a += b; c += d; - b =rol32 (b,6 ); d =rol32 (d,27 ); - d ^= a; b ^= c; +spin_lock_irqsave (&random_ready_list_lock, flags); +if (crng_ready ()) + goto out; - a += b; c += d; - b =rol32 (b,16 ); d =rol32 (d,14 ); - d ^= a; b ^= c; + owner =NULL ; - pool[0 ] = a; pool[1 ] = b; - pool[2 ] = c; pool[3 ] = d; +list_add (&rdy->list, &random_ready_list); + err =0 ; + +out: +spin_unlock_irqrestore (&random_ready_list_lock, flags); + +module_put (owner); + +return err; } +EXPORT_SYMBOL (add_random_ready_callback); + +/* +* Delete a previously registered readiness callback function. +*/ +void del_random_ready_callback (struct random_ready_callback *rdy) +{ +unsigned long flags; +struct module *owner =NULL ; + +spin_lock_irqsave (&random_ready_list_lock, flags); +if (!list_empty (&rdy->list)) { +list_del_init (&rdy->list); + owner = rdy->owner; + } +spin_unlock_irqrestore (&random_ready_list_lock, flags); + +module_put (owner); +} +EXPORT_SYMBOL (del_random_ready_callback);static void process_random_ready_list (void ) {
@@ -339,27 +357,51 @@ static void process_random_ready_list(vospin_unlock_irqrestore (&random_ready_list_lock, flags); } -static void credit_entropy_bits (size_t nbits) +#define warn_unseeded_randomness (previous) \ + _warn_unseeded_randomness(__func__, (void *)_RET_IP_, (previous)) + +static void _warn_unseeded_randomness (const char *func_name,void *caller,void **previous) { -unsigned int entropy_count, orig, add; +#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM +const bool print_once = false; +#else +static bool print_once__read_mostly ; +#endif -if (!nbits) +if (print_once ||crng_ready () || + (previous && (caller ==READ_ONCE (*previous))))return ; - - add =min_t (size_t, nbits,POOL_BITS ); - -do { - orig =READ_ONCE (input_pool.entropy_count); - entropy_count = min_t(unsigned int, POOL_BITS, orig + add); - }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); - -if (crng_init <2 && entropy_count >=POOL_MIN_BITS ) -crng_reseed (); +WRITE_ONCE (*previous, caller); +#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM + print_once = true; +#endif +if (__ratelimit (&unseeded_warning)) +printk_deferred (KERN_NOTICE "random: %s called from %pS with crng_init=%d\n" , + func_name, caller, crng_init); } +/********************************************************************* * -* CRNG using CHACHA20 +* 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 nbytes) +* u32 get_random_u32() +* u64 get_random_u64() +* unsigned int get_random_int() +* 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 integer family of functions may be +* higher performance for one-off random integers, because they do a +* bit of buffering. * *********************************************************************/
@@ -386,123 +428,14 @@ static DEFINE_PER_CPU(struct crng, crngs .generation = ULONG_MAX }; -static DECLARE_WAIT_QUEUE_HEAD (crng_init_wait); - -/* -* crng_fast_load() can be called by code in the interrupt service -* path. So we can't afford to dilly-dally. Returns the number of -* bytes processed from cp. -*/ -static size_t crng_fast_load (const void *cp,size_t len) -{ -unsigned long flags; -const u8 *src = (const u8 *)cp; -size_t ret =0 ; - -if (!spin_trylock_irqsave (&base_crng.lock, flags)) -return 0 ; -if (crng_init !=0 ) { -spin_unlock_irqrestore (&base_crng.lock, flags); -return 0 ; - } -while (len >0 && crng_init_cnt <CRNG_INIT_CNT_THRESH ) { - base_crng.key[crng_init_cnt %sizeof (base_crng.key)] ^= *src; - src++; crng_init_cnt++; len--; ret++; - } -if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { - ++base_crng.generation; - crng_init =1 ; - } -spin_unlock_irqrestore (&base_crng.lock, flags); -if (crng_init ==1 ) -pr_notice ("fast init done\n" ); -return ret; -} - -#ifdef CONFIG_NUMA -static void do_numa_crng_init (struct work_struct *work) -{ -int i; -struct crng_state *crng; -struct crng_state **pool; - - pool =kcalloc (nr_node_ids,sizeof (*pool),GFP_KERNEL |__GFP_NOFAIL); -for_each_online_node (i) { - crng =kmalloc_node (sizeof (struct crng_state ), -GFP_KERNEL | __GFP_NOFAIL, i); -spin_lock_init (&crng->lock); -crng_initialize (crng); - pool[i] = crng; - } -/* pairs with READ_ONCE() in select_crng() */ -if (cmpxchg_release (&crng_node_pool,NULL , pool) !=NULL ) { -for_each_node (i) -kfree (pool[i]); -kfree (pool); - } -} - -static DECLARE_WORK(numa_crng_init_work, do_numa_crng_init); - -static void numa_crng_init (void ) -{ -schedule_work (&numa_crng_init_work); -} - -static struct crng_state *select_crng (void ) -{ -struct crng_state **pool; -int nid =numa_node_id (); - -/* pairs with cmpxchg_release() in do_numa_crng_init() */ - pool =READ_ONCE (crng_node_pool); -if (pool && pool[nid]) -return pool[nid]; - -return &primary_crng; -} -#else -static void numa_crng_init (void ) {} - -static struct crng_state *select_crng (void ) -{ -return &primary_crng; -} -#endif +/* Used by crng_reseed() to extract a new seed from the input pool. */ +static bool drain_entropy (void *buf,size_t nbytes);/* -* crng_slow_load() is called by add_device_randomness, which has two -* attributes. (1) We can't trust the buffer passed to it is -* guaranteed to be unpredictable (so it might not have any entropy at -* all), and (2) it doesn't have the performance constraints of -* crng_fast_load(). -* -* So, we simply hash the contents in with the current key. Finally, -* we do *not* advance crng_init_cnt since buffer we may get may be -* something like a fixed DMI table (for example), which might very -* well be unique to the machine, but is otherwise unvarying. +* This extracts a new crng key from the input pool, but only if there is a +* sufficient amount of entropy available, in order to mitigate bruteforcing +* of newly added bits. */ -static void crng_slow_load (const void *cp,size_t len) -{ -unsigned long flags; -struct blake2s_state hash; - -blake2s_init (&hash,sizeof (base_crng.key)); - -if (!spin_trylock_irqsave (&base_crng.lock, flags)) -return ; -if (crng_init !=0 ) { -spin_unlock_irqrestore (&base_crng.lock, flags); -return ; - } - -blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); -blake2s_update (&hash, cp, len); -blake2s_final (&hash, base_crng.key); - -spin_unlock_irqrestore (&base_crng.lock, flags); -} -static void crng_reseed (void ) {unsigned long flags;
@@ -552,13 +485,11 @@ static void crng_reseed(void) }/* -* The general form here is based on a "fast key erasure RNG" from -* <https://blog.cr.yp.to/20170723-random.html>. It generates a ChaCha -* block using the provided key, and then immediately overwites 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. +* This generates a ChaCha block using the provided key, and then +* immediately overwites 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. */ static void crng_fast_key_erasure(u8 key[CHACHA20_KEY_SIZE], u32 chacha_state[CHACHA20_BLOCK_SIZE / sizeof(u32)],
@@ -645,6 +576,126 @@ static void crng_make_state(u32 chacha_slocal_irq_restore (flags); } +/* +* This function is for crng_init == 0 only. +* +* crng_fast_load() can be called by code in the interrupt service +* path. So we can't afford to dilly-dally. Returns the number of +* bytes processed from cp. +*/ +static size_t crng_fast_load (const void *cp,size_t len) +{ +static int crng_init_cnt =0 ; +unsigned long flags; +const u8 *src = (const u8 *)cp; +size_t ret =0 ; + +if (!spin_trylock_irqsave (&base_crng.lock, flags)) +return 0 ; +if (crng_init !=0 ) { +spin_unlock_irqrestore (&base_crng.lock, flags); +return 0 ; + } +while (len >0 && crng_init_cnt <CRNG_INIT_CNT_THRESH ) { + base_crng.key[crng_init_cnt %sizeof (base_crng.key)] ^= *src; + src++; crng_init_cnt++; len--; ret++; + } +if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { + ++base_crng.generation; + crng_init =1 ; + } +spin_unlock_irqrestore (&base_crng.lock, flags); +if (crng_init ==1 ) +pr_notice ("fast init done\n" ); +return ret; +} + +/* +* This function is for crng_init == 0 only. +* +* crng_slow_load() is called by add_device_randomness, which has two +* attributes. (1) We can't trust the buffer passed to it is +* guaranteed to be unpredictable (so it might not have any entropy at +* all), and (2) it doesn't have the performance constraints of +* crng_fast_load(). +* +* So, we simply hash the contents in with the current key. Finally, +* we do *not* advance crng_init_cnt since buffer we may get may be +* something like a fixed DMI table (for example), which might very +* well be unique to the machine, but is otherwise unvarying. +*/ +static void crng_slow_load (const void *cp,size_t len) +{ +unsigned long flags; +struct blake2s_state hash; + +blake2s_init (&hash,sizeof (base_crng.key)); + +if (!spin_trylock_irqsave (&base_crng.lock, flags)) +return ; +if (crng_init !=0 ) { +spin_unlock_irqrestore (&base_crng.lock, flags); +return ; + } + +blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); +blake2s_update (&hash, cp, len); +blake2s_final (&hash, base_crng.key); + +spin_unlock_irqrestore (&base_crng.lock, flags); +} + +static void _get_random_bytes (void *buf,size_t nbytes) +{ +u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)]; +u8 tmp[CHACHA20_BLOCK_SIZE ]; +size_t len; + +if (!nbytes) +return ; + + len =min_t (size_t,32 , nbytes); +crng_make_state (chacha_state, buf, len); + nbytes -= len; + buf += len; + +while (nbytes) { +if (nbytes <CHACHA20_BLOCK_SIZE ) { +chacha20_block (chacha_state, tmp); +memcpy (buf, tmp, nbytes); +memzero_explicit (tmp,sizeof (tmp)); +break ; + } + +chacha20_block (chacha_state, buf); +if (unlikely (chacha_state[12 ] ==0 )) + ++chacha_state[13 ]; + nbytes -=CHACHA20_BLOCK_SIZE ; + buf +=CHACHA20_BLOCK_SIZE ; + } + +memzero_explicit (chacha_state,sizeof (chacha_state)); +} + +/* +* This function is the exported kernel interface. It returns some +* number of good random numbers, suitable for key generation, seeding +* TCP sequence numbers, etc. It does not rely on the hardware random +* number generator. For random bytes direct from the hardware RNG +* (when available), use get_random_bytes_arch(). 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 nbytes) +{ +static void *previous; + +warn_unseeded_randomness (&previous); +_get_random_bytes (buf, nbytes); +} +EXPORT_SYMBOL (get_random_bytes); +static ssize_t get_random_bytes_user (void __user *buf,size_t nbytes) {bool large_request = nbytes >256 ;
@@ -692,6 +743,265 @@ static ssize_t get_random_bytes_user(voireturn ret; } +/* +* Batched entropy returns random integers. The quality of the random +* number is 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. +*/ +struct batched_entropy { +union { +/* +* 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) * CHACHA20_BLOCK_SIZE. +*/ +u64 entropy_u64[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u64))]; +u32 entropy_u32[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u32))]; + }; +unsigned long generation; +unsigned int position; +}; + + +static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = { + .position =UINT_MAX +}; + +u64 get_random_u64 (void ) +{ +u64 ret; +unsigned long flags; +struct batched_entropy *batch; +static void *previous; +unsigned long next_gen; + +warn_unseeded_randomness (&previous); + +local_irq_save (flags); + batch =raw_cpu_ptr (&batched_entropy_u64); + + next_gen =READ_ONCE (base_crng.generation); +if (batch->position >=ARRAY_SIZE (batch->entropy_u64) || + next_gen != batch->generation) { +_get_random_bytes (batch->entropy_u64,sizeof (batch->entropy_u64)); + batch->position =0 ; + batch->generation = next_gen; + } + + ret = batch->entropy_u64[batch->position]; + batch->entropy_u64[batch->position] =0 ; + ++batch->position; +local_irq_restore (flags); +return ret; +} +EXPORT_SYMBOL (get_random_u64); + +static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = { + .position =UINT_MAX +}; + +u32 get_random_u32 (void ) +{ +u32 ret; +unsigned long flags; +struct batched_entropy *batch; +static void *previous; +unsigned long next_gen; + +warn_unseeded_randomness (&previous); + +local_irq_save (flags); + batch =raw_cpu_ptr (&batched_entropy_u32); + + next_gen =READ_ONCE (base_crng.generation); +if (batch->position >=ARRAY_SIZE (batch->entropy_u32) || + next_gen != batch->generation) { +_get_random_bytes (batch->entropy_u32,sizeof (batch->entropy_u32)); + batch->position =0 ; + batch->generation = next_gen; + } + + ret = batch->entropy_u32[batch->position]; + batch->entropy_u32[batch->position] =0 ; + ++batch->position; +local_irq_restore (flags); +return ret; +} +EXPORT_SYMBOL (get_random_u32); + +/** +* randomize_page - Generate a random, page aligned address +* @start: The smallest acceptable address the caller will take. +* @range: The size of the area, starting at @start, within which the +* random address must fall. +* +* If @start + @range would overflow, @range is capped. +* +* NOTE: Historical use of randomize_range, which this replaces, presumed that +* @start was already page aligned. We now align it regardless. +* +* Return: A page aligned address within [start, start + range). On error, +* @start is returned. +*/ +unsigned long randomize_page (unsigned long start,unsigned long range) +{ +if (!PAGE_ALIGNED (start)) { + range -=PAGE_ALIGN (start) - start; + start =PAGE_ALIGN (start); + } + +if (start >ULONG_MAX - range) + range =ULONG_MAX - start; + + range >>=PAGE_SHIFT ; + +if (range ==0 ) +return start; + +return start + (get_random_long () % range <<PAGE_SHIFT ); +} + +/* +* This function will use the architecture-specific hardware random +* number generator if it is available. It is not recommended for +* use. Use get_random_bytes() instead. It returns the number of +* bytes filled in. +*/ +size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes) +{ +size_t left = nbytes; +u8 *p = buf; + +while (left) { +unsigned long v; +size_t chunk =min_t (size_t, left,sizeof (unsigned long )); + +if (!arch_get_random_long (&v)) +break ; + +memcpy (p, &v, chunk); + p += chunk; + left -= chunk; + } + +return nbytes - left; +} +EXPORT_SYMBOL (get_random_bytes_arch); + +enum { +POOL_BITS =BLAKE2S_HASH_SIZE *8 , +POOL_MIN_BITS =POOL_BITS /* No point in settling for less. */ +}; + +/* +* Static global variables +*/ +static DECLARE_WAIT_QUEUE_HEAD (random_write_wait); + +/********************************************************************** +* +* OS independent entropy store. Here are the functions which handle +* storing entropy in an entropy pool. +* +**********************************************************************/ + +static struct { +struct blake2s_state hash; +spinlock_t lock; +unsigned int entropy_count; +} input_pool = { + .hash.h = {BLAKE2S_IV0 ^ (0x01010000 |BLAKE2S_HASH_SIZE ), +BLAKE2S_IV1 ,BLAKE2S_IV2 ,BLAKE2S_IV3 ,BLAKE2S_IV4 , +BLAKE2S_IV5 ,BLAKE2S_IV6 ,BLAKE2S_IV7 }, + .hash.outlen =BLAKE2S_HASH_SIZE , + .lock =__SPIN_LOCK_UNLOCKED (input_pool.lock), +}; + +static void extract_entropy (void *buf,size_t nbytes); +static bool drain_entropy (void *buf,size_t nbytes); + +static void crng_reseed (void ); + +/* +* This function adds bytes into the entropy "pool". It does not +* update the entropy estimate. The caller should call +* credit_entropy_bits if this is appropriate. +*/ +static void _mix_pool_bytes (const void *in,size_t nbytes) +{ +blake2s_update (&input_pool.hash, in, nbytes); +} + +static void mix_pool_bytes (const void *in,size_t nbytes) +{ +unsigned long flags; + +spin_lock_irqsave (&input_pool.lock, flags); +_mix_pool_bytes (in, nbytes); +spin_unlock_irqrestore (&input_pool.lock, flags); +} + +struct fast_pool { +union { +u32 pool32[4 ]; +u64 pool64[2 ]; + }; +unsigned long last; +u16 reg_idx; +u8 count; +}; + +/* +* This is a fast mixing routine used by the interrupt randomness +* collector. It's hardcoded for an 128 bit pool and assumes that any +* locks that might be needed are taken by the caller. +*/ +static void fast_mix (u32 pool[4 ]) +{ +u32 a = pool[0 ], b = pool[1 ]; +u32 c = pool[2 ], d = pool[3 ]; + + a += b; c += d; + b =rol32 (b,6 ); d =rol32 (d,27 ); + d ^= a; b ^= c; + + a += b; c += d; + b =rol32 (b,16 ); d =rol32 (d,14 ); + d ^= a; b ^= c; + + a += b; c += d; + b =rol32 (b,6 ); d =rol32 (d,27 ); + d ^= a; b ^= c; + + a += b; c += d; + b =rol32 (b,16 ); d =rol32 (d,14 ); + d ^= a; b ^= c; + + pool[0 ] = a; pool[1 ] = b; + pool[2 ] = c; pool[3 ] = d; +} + +static void credit_entropy_bits (size_t nbits) +{ +unsigned int entropy_count, orig, add; + +if (!nbits) +return ; + + add =min_t (size_t, nbits,POOL_BITS ); + +do { + orig =READ_ONCE (input_pool.entropy_count); + entropy_count = min_t(unsigned int, POOL_BITS, orig + add); + }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); + +if (crng_init <2 && entropy_count >=POOL_MIN_BITS ) +crng_reseed (); +} +/********************************************************************* * * Entropy input management
@@ -959,80 +1269,6 @@ static bool drain_entropy(void *buf, sizreturn true; } -#define warn_unseeded_randomness (previous) \ - _warn_unseeded_randomness(__func__, (void *)_RET_IP_, (previous)) - -static void _warn_unseeded_randomness (const char *func_name,void *caller,void **previous) -{ -#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM -const bool print_once = false; -#else -static bool print_once__read_mostly ; -#endif - -if (print_once ||crng_ready () || - (previous && (caller ==READ_ONCE (*previous)))) -return ; -WRITE_ONCE (*previous, caller); -#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM - print_once = true; -#endif -if (__ratelimit (&unseeded_warning)) -pr_notice ("random: %s called from %pS with crng_init=%d\n" , - func_name, caller, crng_init); -} - -/* -* This function is the exported kernel interface. It returns some -* number of good random numbers, suitable for key generation, seeding -* TCP sequence numbers, etc. It does not rely on the hardware random -* number generator. For random bytes direct from the hardware RNG -* (when available), use get_random_bytes_arch(). 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. -*/ -static void _get_random_bytes (void *buf,size_t nbytes) -{ -u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)]; -u8 tmp[CHACHA20_BLOCK_SIZE ]; -size_t len; - -if (!nbytes) -return ; - - len =min_t (size_t,32 , nbytes); -crng_make_state (chacha_state, buf, len); - nbytes -= len; - buf += len; - -while (nbytes) { -if (nbytes <CHACHA20_BLOCK_SIZE ) { -chacha20_block (chacha_state, tmp); -memcpy (buf, tmp, nbytes); -memzero_explicit (tmp,sizeof (tmp)); -break ; - } - -chacha20_block (chacha_state, buf); -if (unlikely (chacha_state[12 ] ==0 )) - ++chacha_state[13 ]; - nbytes -=CHACHA20_BLOCK_SIZE ; - buf +=CHACHA20_BLOCK_SIZE ; - } - -memzero_explicit (chacha_state,sizeof (chacha_state)); -} - -void get_random_bytes (void *buf,size_t nbytes) -{ -static void *previous; - -warn_unseeded_randomness (&previous); -_get_random_bytes (buf, nbytes); -} -EXPORT_SYMBOL (get_random_bytes); -/* * Each time the timer fires, we expect that we got an unpredictable * jump in the cycle counter. Even if the timer is running on another
@@ -1082,134 +1318,6 @@ static void try_to_generate_entropy(voidmix_pool_bytes (&stack.now,sizeof (stack.now)); } -/* -* Wait for the urandom 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_{u32,u64,int,long} -* family of functions. Using any of these functions without first calling -* this function forfeits the guarantee of security. -* -* Returns: 0 if the urandom pool has been seeded. -* -ERESTARTSYS if the function was interrupted by a signal. -*/ -int wait_for_random_bytes (void ) -{ -if (likely (crng_ready ())) -return 0 ; - -do { -int ret; - ret =wait_event_interruptible_timeout (crng_init_wait,crng_ready (),HZ ); -if (ret) -return ret >0 ?0 : ret; - -try_to_generate_entropy (); - }while (!crng_ready ()); - -return 0 ; -} -EXPORT_SYMBOL (wait_for_random_bytes); - -/* -* Returns whether or not the urandom 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_{u32, -* ,u64,int,long} family of functions. -* -* Returns: true if the urandom pool has been seeded. -* false if the urandom pool has not been seeded. -*/ -bool rng_is_initialized (void ) -{ -return crng_ready (); -} -EXPORT_SYMBOL (rng_is_initialized); - -/* -* Add a callback function that will be invoked when the nonblocking -* pool is initialised. -* -* returns: 0 if callback is successfully added -* -EALREADY if pool is already initialised (callback not called) -* -ENOENT if module for callback is not alive -*/ -int add_random_ready_callback (struct random_ready_callback *rdy) -{ -struct module *owner; -unsigned long flags; -int err = -EALREADY ; - -if (crng_ready ()) -return err; - - owner = rdy->owner; -if (!try_module_get (owner)) -return -ENOENT ; - -spin_lock_irqsave (&random_ready_list_lock, flags); -if (crng_ready ()) - goto out; - - owner =NULL ; - -list_add (&rdy->list, &random_ready_list); - err =0 ; - -out: -spin_unlock_irqrestore (&random_ready_list_lock, flags); - -module_put (owner); - -return err; -} -EXPORT_SYMBOL (add_random_ready_callback); - -/* -* Delete a previously registered readiness callback function. -*/ -void del_random_ready_callback (struct random_ready_callback *rdy) -{ -unsigned long flags; -struct module *owner =NULL ; - -spin_lock_irqsave (&random_ready_list_lock, flags); -if (!list_empty (&rdy->list)) { -list_del_init (&rdy->list); - owner = rdy->owner; - } -spin_unlock_irqrestore (&random_ready_list_lock, flags); - -module_put (owner); -} -EXPORT_SYMBOL (del_random_ready_callback); - -/* -* This function will use the architecture-specific hardware random -* number generator if it is available. It is not recommended for -* use. Use get_random_bytes() instead. It returns the number of -* bytes filled in. -*/ -size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes) -{ -size_t left = nbytes; -u8 *p = buf; - -while (left) { -unsigned long v; -size_t chunk =min_t (size_t, left,sizeof (unsigned long )); - -if (!arch_get_random_long (&v)) -break ; - -memcpy (p, &v, chunk); - p += chunk; - left -= chunk; - } - -return nbytes - left; -} -EXPORT_SYMBOL (get_random_bytes_arch); -static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU );static int __init parse_trust_cpu (char *arg) {
@@ -1560,126 +1668,6 @@ struct ctl_table random_table[] = { };#endif /* CONFIG_SYSCTL */ -struct batched_entropy { -union { -/* -* 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) * CHACHA20_BLOCK_SIZE. -*/ -u64 entropy_u64[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u64))]; -u32 entropy_u32[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u32))]; - }; -unsigned long generation; -unsigned int position; -}; - -/* -* Get a random word for internal kernel use only. The quality of the random -* number is 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. -*/ -static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = { - .position =UINT_MAX -}; - -u64 get_random_u64 (void ) -{ -u64 ret; -unsigned long flags; -struct batched_entropy *batch; -static void *previous; -unsigned long next_gen; - -warn_unseeded_randomness (&previous); - -local_irq_save (flags); - batch =raw_cpu_ptr (&batched_entropy_u64); - - next_gen =READ_ONCE (base_crng.generation); -if (batch->position >=ARRAY_SIZE (batch->entropy_u64) || - next_gen != batch->generation) { -_get_random_bytes (batch->entropy_u64,sizeof (batch->entropy_u64)); - batch->position =0 ; - batch->generation = next_gen; - } - - ret = batch->entropy_u64[batch->position]; - batch->entropy_u64[batch->position] =0 ; - ++batch->position; -local_irq_restore (flags); -return ret; -} -EXPORT_SYMBOL (get_random_u64); - -static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = { - .position =UINT_MAX -}; - -u32 get_random_u32 (void ) -{ -u32 ret; -unsigned long flags; -struct batched_entropy *batch; -static void *previous; -unsigned long next_gen; - -warn_unseeded_randomness (&previous); - -local_irq_save (flags); - batch =raw_cpu_ptr (&batched_entropy_u32); - - next_gen =READ_ONCE (base_crng.generation); -if (batch->position >=ARRAY_SIZE (batch->entropy_u32) || - next_gen != batch->generation) { -_get_random_bytes (batch->entropy_u32,sizeof (batch->entropy_u32)); - batch->position =0 ; - batch->generation = next_gen; - } - - ret = batch->entropy_u32[batch->position]; - batch->entropy_u32[batch->position] =0 ; - ++batch->position; -local_irq_restore (flags); -return ret; -} -EXPORT_SYMBOL (get_random_u32); - -/** -* randomize_page - Generate a random, page aligned address -* @start: The smallest acceptable address the caller will take. -* @range: The size of the area, starting at @start, within which the -* random address must fall. -* -* If @start + @range would overflow, @range is capped. -* -* NOTE: Historical use of randomize_range, which this replaces, presumed that -* @start was already page aligned. We now align it regardless. -* -* Return: A page aligned address within [start, start + range). On error, -* @start is returned. -*/ -unsigned long randomize_page (unsigned long start,unsigned long range) -{ -if (!PAGE_ALIGNED (start)) { - range -=PAGE_ALIGN (start) - start; - start =PAGE_ALIGN (start); - } - -if (start >ULONG_MAX - range) - range =ULONG_MAX - start; - - range >>=PAGE_SHIFT ; - -if (range ==0 ) -return start; - -return start + (get_random_long () % range <<PAGE_SHIFT ); -} -/* Interface for in-kernel drivers of true hardware RNGs. * Those devices may produce endless random bits and will be throttled * when our pool is full.
Greg Kroah-Hartman
maintainerPATCH 135/264 random: group entropy extraction functions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a5ed7cb1a7732ef11959332d507889fbc39ebbb4 upstream.
This pulls all of the entropy extraction-focused functions into the third labeled section.
No functional changes.
--- drivers/char/random.c | 216 +++++++++++++++++++++++++------------------------- 1 file changed, 109 insertions(+), 107 deletions(-)
drivers/char/random.c +109 -107
@@ -891,23 +891,36 @@ size_t __must_check get_random_bytes_arc }EXPORT_SYMBOL (get_random_bytes_arch); + +/********************************************************************** +* +* Entropy accumulation and extraction routines. +* +* Callers may add entropy via: +* +* static void mix_pool_bytes(const void *in, size_t nbytes) +* +* After which, if added entropy should be credited: +* +* static void credit_entropy_bits(size_t nbits) +* +* Finally, extract entropy via these two, with the latter one +* setting the entropy count to zero and extracting only if there +* is POOL_MIN_BITS entropy credited prior: +* +* static void extract_entropy(void *buf, size_t nbytes) +* static bool drain_entropy(void *buf, size_t nbytes) +* +**********************************************************************/ +enum {POOL_BITS =BLAKE2S_HASH_SIZE *8 ,POOL_MIN_BITS =POOL_BITS /* No point in settling for less. */ }; -/* -* Static global variables -*/ +/* For notifying userspace should write into /dev/random. */ static DECLARE_WAIT_QUEUE_HEAD (random_write_wait); -/********************************************************************** -* -* OS independent entropy store. Here are the functions which handle -* storing entropy in an entropy pool. -* -**********************************************************************/ - static struct { struct blake2s_state hash; spinlock_t lock;
@@ -920,28 +933,106 @@ static struct { .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock), }; -static void extract_entropy (void *buf,size_t nbytes); -static bool drain_entropy (void *buf,size_t nbytes); - -static void crng_reseed (void ); +static void _mix_pool_bytes (const void *in,size_t nbytes) +{ +blake2s_update (&input_pool.hash, in, nbytes); +}/* * This function adds bytes into the entropy "pool". It does not * update the entropy estimate. The caller should call * credit_entropy_bits if this is appropriate. */ -static void _mix_pool_bytes (const void *in,size_t nbytes) +static void mix_pool_bytes (const void *in,size_t nbytes) { -blake2s_update (&input_pool.hash, in, nbytes); +unsigned long flags; + +spin_lock_irqsave (&input_pool.lock, flags); +_mix_pool_bytes (in, nbytes); +spin_unlock_irqrestore (&input_pool.lock, flags); } -static void mix_pool_bytes (const void *in,size_t nbytes) +static void credit_entropy_bits (size_t nbits) +{ +unsigned int entropy_count, orig, add; + +if (!nbits) +return ; + + add =min_t (size_t, nbits,POOL_BITS ); + +do { + orig =READ_ONCE (input_pool.entropy_count); + entropy_count = min_t(unsigned int, POOL_BITS, orig + add); + }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); + +if (crng_init <2 && entropy_count >=POOL_MIN_BITS ) +crng_reseed (); +} + +/* +* This is an HKDF-like construction for using the hashed collected entropy +* as a PRF key, that's then expanded block-by-block. +*/ +static void extract_entropy (void *buf,size_t nbytes) {unsigned long flags; +u8 seed[BLAKE2S_HASH_SIZE ], next_key[BLAKE2S_HASH_SIZE ]; +struct { +unsigned long rdseed[32 /sizeof (long )]; +size_t counter; + } block; +size_t i; + +for (i =0 ; i <ARRAY_SIZE (block.rdseed); ++i) { +if (!arch_get_random_seed_long (&block.rdseed[i]) && + !arch_get_random_long (&block.rdseed[i])) + block.rdseed[i] =random_get_entropy (); + }spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (in, nbytes); + +/* seed = HASHPRF(last_key, entropy_input) */ +blake2s_final (&input_pool.hash, seed); + +/* next_key = HASHPRF(seed, RDSEED || 0) */ + block.counter =0 ; +blake2s (next_key, (u8 *)&block, seed,sizeof (next_key),sizeof (block),sizeof (seed)); +blake2s_init_key (&input_pool.hash,BLAKE2S_HASH_SIZE , next_key,sizeof (next_key)); +spin_unlock_irqrestore (&input_pool.lock, flags); +memzero_explicit (next_key,sizeof (next_key)); + +while (nbytes) { + i =min_t (size_t, nbytes,BLAKE2S_HASH_SIZE ); +/* output = HASHPRF(seed, RDSEED || ++counter) */ + ++block.counter; +blake2s (buf, (u8 *)&block, seed, i,sizeof (block),sizeof (seed)); + nbytes -= i; + buf += i; + } + +memzero_explicit (seed,sizeof (seed)); +memzero_explicit (&block,sizeof (block)); +} + +/* +* First we make sure we have POOL_MIN_BITS of entropy in the pool, and then we +* set the entropy count to zero (but don't actually touch any data). Only then +* can we extract a new key with extract_entropy(). +*/ +static bool drain_entropy (void *buf,size_t nbytes) +{ +unsigned int entropy_count; +do { + entropy_count =READ_ONCE (input_pool.entropy_count); +if (entropy_count <POOL_MIN_BITS ) +return false; + }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); +extract_entropy (buf, nbytes); +wake_up_interruptible (&random_write_wait); +kill_fasync (&fasync,SIGIO ,POLL_OUT ); +return true; }struct fast_pool {
@@ -984,24 +1075,6 @@ static void fast_mix(u32 pool[4]) pool[2 ] = c; pool[3 ] = d; } -static void credit_entropy_bits (size_t nbits) -{ -unsigned int entropy_count, orig, add; - -if (!nbits) -return ; - - add =min_t (size_t, nbits,POOL_BITS ); - -do { - orig =READ_ONCE (input_pool.entropy_count); - entropy_count = min_t(unsigned int, POOL_BITS, orig + add); - }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); - -if (crng_init <2 && entropy_count >=POOL_MIN_BITS ) -crng_reseed (); -} -/********************************************************************* * * Entropy input management
@@ -1198,77 +1271,6 @@ void add_disk_randomness(struct gendiskEXPORT_SYMBOL_GPL (add_disk_randomness);#endif -/********************************************************************* -* -* Entropy extraction routines -* -*********************************************************************/ - -/* -* This is an HKDF-like construction for using the hashed collected entropy -* as a PRF key, that's then expanded block-by-block. -*/ -static void extract_entropy (void *buf,size_t nbytes) -{ -unsigned long flags; -u8 seed[BLAKE2S_HASH_SIZE ], next_key[BLAKE2S_HASH_SIZE ]; -struct { -unsigned long rdseed[32 /sizeof (long )]; -size_t counter; - } block; -size_t i; - -for (i =0 ; i <ARRAY_SIZE (block.rdseed); ++i) { -if (!arch_get_random_seed_long (&block.rdseed[i]) && - !arch_get_random_long (&block.rdseed[i])) - block.rdseed[i] =random_get_entropy (); - } - -spin_lock_irqsave (&input_pool.lock, flags); - -/* seed = HASHPRF(last_key, entropy_input) */ -blake2s_final (&input_pool.hash, seed); - -/* next_key = HASHPRF(seed, RDSEED || 0) */ - block.counter =0 ; -blake2s (next_key, (u8 *)&block, seed,sizeof (next_key),sizeof (block),sizeof (seed)); -blake2s_init_key (&input_pool.hash,BLAKE2S_HASH_SIZE , next_key,sizeof (next_key)); - -spin_unlock_irqrestore (&input_pool.lock, flags); -memzero_explicit (next_key,sizeof (next_key)); - -while (nbytes) { - i =min_t (size_t, nbytes,BLAKE2S_HASH_SIZE ); -/* output = HASHPRF(seed, RDSEED || ++counter) */ - ++block.counter; -blake2s (buf, (u8 *)&block, seed, i,sizeof (block),sizeof (seed)); - nbytes -= i; - buf += i; - } - -memzero_explicit (seed,sizeof (seed)); -memzero_explicit (&block,sizeof (block)); -} - -/* -* First we make sure we have POOL_MIN_BITS of entropy in the pool, and then we -* set the entropy count to zero (but don't actually touch any data). Only then -* can we extract a new key with extract_entropy(). -*/ -static bool drain_entropy (void *buf,size_t nbytes) -{ -unsigned int entropy_count; -do { - entropy_count =READ_ONCE (input_pool.entropy_count); -if (entropy_count <POOL_MIN_BITS ) -return false; - }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); -extract_entropy (buf, nbytes); -wake_up_interruptible (&random_write_wait); -kill_fasync (&fasync,SIGIO ,POLL_OUT ); -return true; -} -/* * Each time the timer fires, we expect that we got an unpredictable * jump in the cycle counter. Even if the timer is running on another
Greg Kroah-Hartman
maintainerPATCH 136/264 random: group entropy collection functions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 92c653cf14400946f376a29b828d6af7e01f38dd upstream.
This pulls all of the entropy collection-focused functions into the fourth labeled section.
No functional changes.
--- drivers/char/random.c | 370 +++++++++++++++++++++++++++----------------------- 1 file changed, 206 insertions(+), 164 deletions(-)
drivers/char/random.c +206 -164
@@ -1035,60 +1035,112 @@ static bool drain_entropy(void *buf, sizreturn true; } -struct fast_pool { -union { -u32 pool32[4 ]; -u64 pool64[2 ]; - }; -unsigned long last; -u16 reg_idx; -u8 count; -}; + +/********************************************************************** +* +* Entropy collection routines. +* +* The following exported functions are used for pushing entropy into +* the above entropy accumulation routines: +* +* void add_device_randomness(const void *buf, size_t size); +* void add_input_randomness(unsigned int type, unsigned int code, +* unsigned int value); +* void add_disk_randomness(struct gendisk *disk); +* void add_hwgenerator_randomness(const void *buffer, size_t count, +* size_t entropy); +* void add_bootloader_randomness(const void *buf, size_t size); +* void add_interrupt_randomness(int irq); +* +* add_device_randomness() adds data to the input pool that +* is likely to differ between two devices (or possibly even per boot). +* This would be things like MAC addresses or serial numbers, or the +* read-out of the RTC. This does *not* credit any actual entropy to +* the pool, but it initializes the pool to different values for devices +* that might otherwise be identical and have very little entropy +* available to them (particularly common in the embedded world). +* +* add_input_randomness() uses the input layer interrupt timing, as well +* as the event type information from the hardware. +* +* add_disk_randomness() uses what amounts to the seek time of block +* layer request events, on a per-disk_devt basis, as input to the +* entropy pool. Note that high-speed solid state drives with very low +* seek times do not make for good sources of entropy, as their seek +* times are usually fairly consistent. +* +* The above two routines try to estimate how many bits of entropy +* to credit. They do this by keeping track of the first and second +* order deltas of the event timings. +* +* add_hwgenerator_randomness() is for true hardware RNGs, and will credit +* entropy as specified by the caller. If the entropy pool is full it will +* block until more entropy is needed. +* +* add_bootloader_randomness() is the same as add_hwgenerator_randomness() or +* add_device_randomness(), depending on whether or not the configuration +* option CONFIG_RANDOM_TRUST_BOOTLOADER is set. +* +* add_interrupt_randomness() uses the interrupt timing as random +* inputs to the entropy pool. Using the cycle counters and the irq source +* as inputs, it feeds the input pool roughly once a second or after 64 +* interrupts, crediting 1 bit of entropy for whichever comes first. +* +**********************************************************************/ + +static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU ); +static int __init parse_trust_cpu (char *arg) +{ +return kstrtobool (arg, &trust_cpu); +} +early_param ("random.trust_cpu" , parse_trust_cpu);/* -* This is a fast mixing routine used by the interrupt randomness -* collector. It's hardcoded for an 128 bit pool and assumes that any -* locks that might be needed are taken by the caller. +* The first collection of entropy occurs at system boot while interrupts +* are still turned off. Here we push in RDSEED, a timestamp, and utsname(). +* Depending on the above configuration knob, RDSEED may be considered +* sufficient for initialization. Note that much earlier setup may already +* have pushed entropy into the input pool by the time we get here. */ -static void fast_mix (u32 pool[4 ]) +int __init rand_initialize (void ) { -u32 a = pool[0 ], b = pool[1 ]; -u32 c = pool[2 ], d = pool[3 ]; - - a += b; c += d; - b =rol32 (b,6 ); d =rol32 (d,27 ); - d ^= a; b ^= c; +size_t i; +ktime_t now =ktime_get_real (); +bool arch_init = true; +unsigned long rv; - a += b; c += d; - b =rol32 (b,16 ); d =rol32 (d,14 ); - d ^= a; b ^= c; +for (i =0 ; i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) { +if (!arch_get_random_seed_long_early (&rv) && + !arch_get_random_long_early (&rv)) { + rv =random_get_entropy (); + arch_init = false; + } +mix_pool_bytes (&rv,sizeof (rv)); + } +mix_pool_bytes (&now,sizeof (now)); +mix_pool_bytes (utsname (),sizeof (*(utsname ()))); - a += b; c += d; - b =rol32 (b,6 ); d =rol32 (d,27 ); - d ^= a; b ^= c; +extract_entropy (base_crng.key,sizeof (base_crng.key)); + ++base_crng.generation; - a += b; c += d; - b =rol32 (b,16 ); d =rol32 (d,14 ); - d ^= a; b ^= c; +if (arch_init && trust_cpu && crng_init <2 ) { + crng_init =2 ; +pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); + } - pool[0 ] = a; pool[1 ] = b; - pool[2 ] = c; pool[3 ] = d; +if (ratelimit_disable) { + urandom_warning.interval =0 ; + unseeded_warning.interval =0 ; + } +return 0 ; } -/********************************************************************* -* -* Entropy input management -* -*********************************************************************/ -/* There is one of these per entropy source */ struct timer_rand_state {cycles_t last_time;long last_delta, last_delta2; }; -#define INIT_TIMER_RAND_STATE { INITIAL_JIFFIES, }; -/* * Add device- or boot-specific data to the input pool to help * initialize it.
@@ -1112,8 +1164,6 @@ void add_device_randomness(const void *b }EXPORT_SYMBOL (add_device_randomness); -static struct timer_rand_state input_timer_state =INIT_TIMER_RAND_STATE ; -/* * This function adds entropy to the entropy "pool" by using timing * delays. It uses the timer_rand_state structure to make an estimate
@@ -1175,8 +1225,9 @@ void add_input_randomness(unsigned int t unsigned int value) {static unsigned char last_value; +static struct timer_rand_state input_timer_state = {INITIAL_JIFFIES }; -/* ignore autorepeat and the like */ +/* Ignore autorepeat and the like. */ if (value == last_value)return ;
@@ -1186,6 +1237,119 @@ void add_input_randomness(unsigned int t }EXPORT_SYMBOL_GPL (add_input_randomness); +#ifdef CONFIG_BLOCK +void add_disk_randomness (struct gendisk *disk) +{ +if (!disk || !disk->random) +return ; +/* First major is 1, so we get >= 0x200 here. */ +add_timer_randomness (disk->random,0x100 +disk_devt (disk)); +} +EXPORT_SYMBOL_GPL (add_disk_randomness); + +void rand_initialize_disk (struct gendisk *disk) +{ +struct timer_rand_state *state; + +/* +* If kzalloc returns null, we just won't use that entropy +* source. +*/ + state =kzalloc (sizeof (struct timer_rand_state ),GFP_KERNEL ); +if (state) { + state->last_time =INITIAL_JIFFIES ; + disk->random = state; + } +} +#endif + +/* +* Interface for in-kernel drivers of true hardware RNGs. +* Those devices may produce endless random bits and will be throttled +* when our pool is full. +*/ +void add_hwgenerator_randomness (const void *buffer,size_t count, +size_t entropy) +{ +if (unlikely (crng_init ==0 )) { +size_t ret =crng_fast_load (buffer, count); +mix_pool_bytes (buffer, ret); + count -= ret; + buffer += ret; +if (!count || crng_init ==0 ) +return ; + } + +/* +* Throttle writing if we're above the trickle threshold. +* We'll be woken up again once below POOL_MIN_BITS, when +* the calling thread is about to terminate, or once +* CRNG_RESEED_INTERVAL has elapsed. +*/ +wait_event_interruptible_timeout (random_write_wait, + !system_wq ||kthread_should_stop () || + input_pool.entropy_count <POOL_MIN_BITS , +CRNG_RESEED_INTERVAL ); +mix_pool_bytes (buffer, count); +credit_entropy_bits (entropy); +} +EXPORT_SYMBOL_GPL (add_hwgenerator_randomness); + +/* +* Handle random seed passed by bootloader. +* If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise +* it would be regarded as device data. +* The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER. +*/ +void add_bootloader_randomness (const void *buf,size_t size) +{ +if (IS_ENABLED (CONFIG_RANDOM_TRUST_BOOTLOADER )) +add_hwgenerator_randomness (buf, size, size *8 ); +else +add_device_randomness (buf, size); +} +EXPORT_SYMBOL_GPL (add_bootloader_randomness); + +struct fast_pool { +union { +u32 pool32[4 ]; +u64 pool64[2 ]; + }; +unsigned long last; +u16 reg_idx; +u8 count; +}; + +/* +* This is a fast mixing routine used by the interrupt randomness +* collector. It's hardcoded for an 128 bit pool and assumes that any +* locks that might be needed are taken by the caller. +*/ +static void fast_mix (u32 pool[4 ]) +{ +u32 a = pool[0 ], b = pool[1 ]; +u32 c = pool[2 ], d = pool[3 ]; + + a += b; c += d; + b =rol32 (b,6 ); d =rol32 (d,27 ); + d ^= a; b ^= c; + + a += b; c += d; + b =rol32 (b,16 ); d =rol32 (d,14 ); + d ^= a; b ^= c; + + a += b; c += d; + b =rol32 (b,6 ); d =rol32 (d,27 ); + d ^= a; b ^= c; + + a += b; c += d; + b =rol32 (b,16 ); d =rol32 (d,14 ); + d ^= a; b ^= c; + + pool[0 ] = a; pool[1 ] = b; + pool[2 ] = c; pool[3 ] = d; +} + static DEFINE_PER_CPU(struct fast_pool, irq_randomness);static u32 get_reg (struct fast_pool *f,struct pt_regs *regs)
@@ -1255,22 +1419,11 @@ void add_interrupt_randomness(int irq) fast_pool->count =0 ; -/* award one bit for the contents of the fast pool */ +/* Award one bit for the contents of the fast pool. */ credit_entropy_bits (1 ); }EXPORT_SYMBOL_GPL (add_interrupt_randomness); -#ifdef CONFIG_BLOCK -void add_disk_randomness (struct gendisk *disk) -{ -if (!disk || !disk->random) -return ; -/* first major is 1, so we get >= 0x200 here */ -add_timer_randomness (disk->random,0x100 +disk_devt (disk)); -} -EXPORT_SYMBOL_GPL (add_disk_randomness); -#endif -/* * Each time the timer fires, we expect that we got an unpredictable * jump in the cycle counter. Even if the timer is running on another
@@ -1320,73 +1473,6 @@ static void try_to_generate_entropy(voidmix_pool_bytes (&stack.now,sizeof (stack.now)); } -static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU ); -static int __init parse_trust_cpu (char *arg) -{ -return kstrtobool (arg, &trust_cpu); -} -early_param ("random.trust_cpu" , parse_trust_cpu); - -/* -* Note that setup_arch() may call add_device_randomness() -* long before we get here. This allows seeding of the pools -* with some platform dependent data very early in the boot -* process. But it limits our options here. We must use -* statically allocated structures that already have all -* initializations complete at compile time. We should also -* take care not to overwrite the precious per platform data -* we were given. -*/ -int __init rand_initialize (void ) -{ -size_t i; -ktime_t now =ktime_get_real (); -bool arch_init = true; -unsigned long rv; - -for (i =0 ; i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) { -if (!arch_get_random_seed_long_early (&rv) && - !arch_get_random_long_early (&rv)) { - rv =random_get_entropy (); - arch_init = false; - } -mix_pool_bytes (&rv,sizeof (rv)); - } -mix_pool_bytes (&now,sizeof (now)); -mix_pool_bytes (utsname (),sizeof (*(utsname ()))); - -extract_entropy (base_crng.key,sizeof (base_crng.key)); - ++base_crng.generation; - -if (arch_init && trust_cpu && crng_init <2 ) { - crng_init =2 ; -pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); - } - -if (ratelimit_disable) { - urandom_warning.interval =0 ; - unseeded_warning.interval =0 ; - } -return 0 ; -} - -#ifdef CONFIG_BLOCK -void rand_initialize_disk (struct gendisk *disk) -{ -struct timer_rand_state *state; - -/* -* If kzalloc returns null, we just won't use that entropy -* source. -*/ - state =kzalloc (sizeof (struct timer_rand_state ),GFP_KERNEL ); -if (state) { - state->last_time =INITIAL_JIFFIES ; - disk->random = state; - } -} -#endif -static ssize_t urandom_read (struct file *file,char __user *buf,size_t nbytes,loff_t *ppos) {
@@ -1669,47 +1755,3 @@ struct ctl_table random_table[] = { { } };#endif /* CONFIG_SYSCTL */ - -/* Interface for in-kernel drivers of true hardware RNGs. -* Those devices may produce endless random bits and will be throttled -* when our pool is full. -*/ -void add_hwgenerator_randomness (const void *buffer,size_t count, -size_t entropy) -{ -if (unlikely (crng_init ==0 )) { -size_t ret =crng_fast_load (buffer, count); -mix_pool_bytes (buffer, ret); - count -= ret; - buffer += ret; -if (!count || crng_init ==0 ) -return ; - } - -/* Throttle writing if we're above the trickle threshold. -* We'll be woken up again once below POOL_MIN_BITS, when -* the calling thread is about to terminate, or once -* CRNG_RESEED_INTERVAL has elapsed. -*/ -wait_event_interruptible_timeout (random_write_wait, - !system_wq ||kthread_should_stop () || - input_pool.entropy_count <POOL_MIN_BITS , -CRNG_RESEED_INTERVAL ); -mix_pool_bytes (buffer, count); -credit_entropy_bits (entropy); -} -EXPORT_SYMBOL_GPL (add_hwgenerator_randomness); - -/* Handle random seed passed by bootloader. -* If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise -* it would be regarded as device data. -* The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER. -*/ -void add_bootloader_randomness (const void *buf,size_t size) -{ -if (IS_ENABLED (CONFIG_RANDOM_TRUST_BOOTLOADER )) -add_hwgenerator_randomness (buf, size, size *8 ); -else -add_device_randomness (buf, size); -} -EXPORT_SYMBOL_GPL (add_bootloader_randomness);
Greg Kroah-Hartman
maintainerPATCH 137/264 random: group userspace read/write functions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a6adf8e7a605250b911e94793fd077933709ff9e upstream.
This pulls all of the userspace read/write-focused functions into the fifth labeled section.
No functional changes.
--- drivers/char/random.c | 125 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 77 insertions(+), 48 deletions(-)
drivers/char/random.c +77 -48
@@ -1473,30 +1473,61 @@ static void try_to_generate_entropy(voidmix_pool_bytes (&stack.now,sizeof (stack.now)); } -static ssize_t urandom_read (struct file *file,char __user *buf,size_t nbytes, -loff_t *ppos) + +/********************************************************************** +* +* Userspace reader/writer interfaces. +* +* getrandom(2) is the primary modern interface into the RNG and should +* be used in preference to anything else. +* +* Reading from /dev/random has the same functionality as calling +* getrandom(2) with flags=0. In earlier versions, however, it had +* vastly different semantics and should therefore be avoided, to +* prevent backwards compatibility issues. +* +* Reading from /dev/urandom has the same functionality as calling +* getrandom(2) with flags=GRND_INSECURE. Because it does not block +* waiting for the RNG to be ready, it should not be used. +* +* Writing to either /dev/random or /dev/urandom adds entropy to +* the input pool but does not credit it. +* +* Polling on /dev/random indicates when the RNG is initialized, on +* the read side, and when it wants new entropy, on the write side. +* +* Both /dev/random and /dev/urandom have the same set of ioctls for +* adding entropy, getting the entropy count, zeroing the count, and +* reseeding the crng. +* +**********************************************************************/ + +SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int, + flags) { -static int maxwarn =10 ; +if (flags & ~(GRND_NONBLOCK |GRND_RANDOM |GRND_INSECURE )) +return -EINVAL ; -if (!crng_ready () && maxwarn >0 ) { - maxwarn--; -if (__ratelimit (&urandom_warning)) -pr_notice ("%s: uninitialized urandom read (%zd bytes read)\n" , - current->comm, nbytes); - } +/* +* Requesting insecure and blocking randomness at the same time makes +* no sense. +*/ +if ((flags & (GRND_INSECURE |GRND_RANDOM )) == (GRND_INSECURE |GRND_RANDOM )) +return -EINVAL ; -return get_random_bytes_user (buf, nbytes); -} +if (count >INT_MAX ) + count =INT_MAX ; -static ssize_t random_read (struct file *file,char __user *buf,size_t nbytes, -loff_t *ppos) -{ -int ret; +if (!(flags &GRND_INSECURE ) && !crng_ready ()) { +int ret; - ret =wait_for_random_bytes (); -if (ret !=0 ) -return ret; -return get_random_bytes_user (buf, nbytes); +if (flags &GRND_NONBLOCK ) +return -EAGAIN ; + ret =wait_for_random_bytes (); +if (unlikely (ret)) +return ret; + } +return get_random_bytes_user (buf, count); }static unsigned int random_poll (struct file *file,poll_table *wait)
@@ -1548,6 +1579,32 @@ static ssize_t random_write(struct filereturn (ssize_t )count; } +static ssize_t urandom_read (struct file *file,char __user *buf,size_t nbytes, +loff_t *ppos) +{ +static int maxwarn =10 ; + +if (!crng_ready () && maxwarn >0 ) { + maxwarn--; +if (__ratelimit (&urandom_warning)) +pr_notice ("%s: uninitialized urandom read (%zd bytes read)\n" , + current->comm, nbytes); + } + +return get_random_bytes_user (buf, nbytes); +} + +static ssize_t random_read (struct file *file,char __user *buf,size_t nbytes, +loff_t *ppos) +{ +int ret; + + ret =wait_for_random_bytes (); +if (ret !=0 ) +return ret; +return get_random_bytes_user (buf, nbytes); +} +static long random_ioctl (struct file *f,unsigned int cmd,unsigned long arg) {int size, ent_count;
@@ -1556,7 +1613,7 @@ static long random_ioctl(struct file *f,switch (cmd) {case RNDGETENTCNT : -/* inherently racy, no point locking */ +/* Inherently racy, no point locking. */ if (put_user (input_pool.entropy_count, p))return -EFAULT ;return 0 ;
@@ -1630,34 +1687,6 @@ const struct file_operations urandom_fop .llseek = noop_llseek, }; -SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int, - flags) -{ -if (flags & ~(GRND_NONBLOCK |GRND_RANDOM |GRND_INSECURE )) -return -EINVAL ; - -/* -* Requesting insecure and blocking randomness at the same time makes -* no sense. -*/ -if ((flags & (GRND_INSECURE |GRND_RANDOM )) == (GRND_INSECURE |GRND_RANDOM )) -return -EINVAL ; - -if (count >INT_MAX ) - count =INT_MAX ; - -if (!(flags &GRND_INSECURE ) && !crng_ready ()) { -int ret; - -if (flags &GRND_NONBLOCK ) -return -EAGAIN ; - ret =wait_for_random_bytes (); -if (unlikely (ret)) -return ret; - } -return get_random_bytes_user (buf, count); -} -/******************************************************************** * * Sysctl interface
Greg Kroah-Hartman
maintainerPATCH 138/264 random: group sysctl functions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 0deff3c43206c24e746b1410f11125707ad3040e upstream.
This pulls all of the sysctl-focused functions into the sixth labeled section.
No functional changes.
--- drivers/char/random.c | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-)
drivers/char/random.c +30 -5
@@ -1687,9 +1687,34 @@ const struct file_operations urandom_fop .llseek = noop_llseek, }; +/******************************************************************** * -* Sysctl interface +* Sysctl interface. +* +* These are partly unused legacy knobs with dummy values to not break +* userspace and partly still useful things. They are usually accessible +* in /proc/sys/kernel/random/ and are as follows: +* +* - boot_id - a UUID representing the current boot. +* +* - uuid - a random UUID, different each time the file is read. +* +* - poolsize - the number of bits of entropy that the input pool can +* hold, tied to the POOL_BITS constant. +* +* - entropy_avail - the number of bits of entropy currently in the +* input pool. Always <= poolsize. +* +* - write_wakeup_threshold - the amount of entropy in the input pool +* below which write polls to /dev/random will unblock, requesting +* more entropy, tied to the POOL_MIN_BITS constant. It is writable +* to avoid breaking old userspaces, but writing to it does not +* change any behavior of the RNG. +* +* - urandom_min_reseed_secs - fixed to the meaningless value "60". +* It is writable to avoid breaking old userspaces, but writing +* to it does not change any behavior of the RNG. * ********************************************************************/
@@ -1697,8 +1722,8 @@ const struct file_operations urandom_fop#include <linux/sysctl.h> -static int random_min_urandom_seed =60 ; -static int random_write_wakeup_bits =POOL_MIN_BITS ; +static int sysctl_random_min_urandom_seed =60 ; +static int sysctl_random_write_wakeup_bits =POOL_MIN_BITS ;static int sysctl_poolsize =POOL_BITS ;static char sysctl_bootid[16 ];
@@ -1756,14 +1781,14 @@ struct ctl_table random_table[] = { }, { .procname = "write_wakeup_threshold", - .data = &random_write_wakeup_bits, + .data = &sysctl_random_write_wakeup_bits, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "urandom_min_reseed_secs", - .data = &random_min_urandom_seed, + .data = &sysctl_random_min_urandom_seed, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec,
Greg Kroah-Hartman
maintainerPATCH 139/264 random: rewrite header introductory comment
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 5f75d9f3babea8ae0a2d06724656874f41d317f5 upstream.
Now that we've re-documented the various sections, we can remove the outdated text here and replace it with a high-level overview.
--- drivers/char/random.c | 179 +++++--------------------------------------------- 1 file changed, 19 insertions(+), 160 deletions(-)
drivers/char/random.c +19 -160
@@ -2,168 +2,27 @@/* * Copyright (C) 2017-2022 Jason A. Donenfeld <[email protected]>. All Rights Reserved. * Copyright Matt Mackall <[email protected]>, 2003, 2004, 2005 -* Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All -* rights reserved. -*/ - -/* -* Exported interfaces ---- output -* =============================== -* -* There are four exported interfaces; two for use within the kernel, -* and two for use from userspace. -* -* Exported interfaces ---- userspace output -* ----------------------------------------- -* -* The userspace interfaces are two character devices /dev/random and -* /dev/urandom. /dev/random is suitable for use when very high -* quality randomness is desired (for example, for key generation or -* one-time pads), as it will only return a maximum of the number of -* bits of randomness (as estimated by the random number generator) -* contained in the entropy pool. -* -* The /dev/urandom device does not have this limit, and will return -* as many bytes as are requested. As more and more random bytes are -* requested without giving time for the entropy pool to recharge, -* this will result in random numbers that are merely cryptographically -* strong. For many applications, however, this is acceptable. -* -* Exported interfaces ---- kernel output -* -------------------------------------- -* -* The primary kernel interfaces are: -* -* void get_random_bytes(void *buf, size_t nbytes); -* u32 get_random_u32() -* u64 get_random_u64() -* unsigned int get_random_int() -* 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 get_random_{u32,u64,int,long}() family -* of functions may be higher performance for one-off random integers, -* because they do a bit of buffering. -* -* prandom_u32() -* ------------- -* -* For even weaker applications, see the pseudorandom generator -* prandom_u32(), prandom_max(), and prandom_bytes(). If the random -* numbers aren't security-critical at all, these are *far* cheaper. -* Useful for self-tests, random error simulation, randomized backoffs, -* and any other application where you trust that nobody is trying to -* maliciously mess with you by guessing the "random" numbers. -* -* Exported interfaces ---- input -* ============================== -* -* The current exported interfaces for gathering environmental noise -* from the devices are: -* -* void add_device_randomness(const void *buf, size_t size); -* void add_input_randomness(unsigned int type, unsigned int code, -* unsigned int value); -* void add_interrupt_randomness(int irq); -* void add_disk_randomness(struct gendisk *disk); -* void add_hwgenerator_randomness(const void *buffer, size_t count, -* size_t entropy); -* void add_bootloader_randomness(const void *buf, size_t size); -* -* add_device_randomness() is for adding data to the random pool that -* is likely to differ between two devices (or possibly even per boot). -* This would be things like MAC addresses or serial numbers, or the -* read-out of the RTC. This does *not* add any actual entropy to the -* pool, but it initializes the pool to different values for devices -* that might otherwise be identical and have very little entropy -* available to them (particularly common in the embedded world). -* -* add_input_randomness() uses the input layer interrupt timing, as well as -* the event type information from the hardware. -* -* add_interrupt_randomness() uses the interrupt timing as random -* inputs to the entropy pool. Using the cycle counters and the irq source -* as inputs, it feeds the randomness roughly once a second. -* -* add_disk_randomness() uses what amounts to the seek time of block -* layer request events, on a per-disk_devt basis, as input to the -* entropy pool. Note that high-speed solid state drives with very low -* seek times do not make for good sources of entropy, as their seek -* times are usually fairly consistent. -* -* All of these routines try to estimate how many bits of randomness a -* particular randomness source. They do this by keeping track of the -* first and second order deltas of the event timings. -* -* add_hwgenerator_randomness() is for true hardware RNGs, and will credit -* entropy as specified by the caller. If the entropy pool is full it will -* block until more entropy is needed. -* -* add_bootloader_randomness() is the same as add_hwgenerator_randomness() or -* add_device_randomness(), depending on whether or not the configuration -* option CONFIG_RANDOM_TRUST_BOOTLOADER is set. -* -* Ensuring unpredictability at system startup -* ============================================ -* -* When any operating system starts up, it will go through a sequence -* of actions that are fairly predictable by an adversary, especially -* if the start-up does not involve interaction with a human operator. -* This reduces the actual number of bits of unpredictability in the -* entropy pool below the value in entropy_count. In order to -* counteract this effect, it helps to carry information in the -* entropy pool across shut-downs and start-ups. To do this, put the -* following lines an appropriate script which is run during the boot -* sequence: -* -* echo "Initializing random number generator..." -* random_seed=/var/run/random-seed -* # Carry a random seed from start-up to start-up -* # Load and then save the whole entropy pool -* if [ -f $random_seed ]; then -* cat $random_seed >/dev/urandom -* else -* touch $random_seed -* fi -* chmod 600 $random_seed -* dd if=/dev/urandom of=$random_seed count=1 bs=512 -* -* and the following lines in an appropriate script which is run as -* the system is shutdown: -* -* # Carry a random seed from shut-down to start-up -* # Save the whole entropy pool -* echo "Saving random seed..." -* random_seed=/var/run/random-seed -* touch $random_seed -* chmod 600 $random_seed -* dd if=/dev/urandom of=$random_seed count=1 bs=512 -* -* For example, on most modern systems using the System V init -* scripts, such code fragments would be found in -* /etc/rc.d/init.d/random. On older Linux systems, the correct script -* location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0. -* -* Effectively, these commands cause the contents of the entropy pool -* to be saved at shut-down time and reloaded into the entropy pool at -* start-up. (The 'dd' in the addition to the bootup script is to -* make sure that /etc/random-seed is different for every start-up, -* even if the system crashes without executing rc.0.) Even with -* complete knowledge of the start-up activities, predicting the state -* of the entropy pool requires knowledge of the previous history of -* the system. -* -* Configuring the /dev/random driver under Linux -* ============================================== +* Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All rights reserved. * -* The /dev/random driver under Linux uses minor numbers 8 and 9 of -* the /dev/mem major number (#1). So if your system does not have -* /dev/random and /dev/urandom created already, they can be created -* by using the commands: +* This driver produces cryptographically secure pseudorandom data. It is divided +* into roughly six sections, each with a section header: * -* mknod /dev/random c 1 8 -* mknod /dev/urandom c 1 9 +* - 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. 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 and credit it. There is currently no Fortuna-like scheduler +* involved, which can lead to malicious entropy sources causing a premature +* reseed, and the entropy estimates are, at best, conservative guesses. */ #define pr_fmt (fmt) KBUILD_MODNAME ": " fmt
Greg Kroah-Hartman
maintainerPATCH 140/264 workqueue: make workqueue available early during boot
In reply to Greg Kroah-HartmanFrom: Tejun Heo <[email protected]>
commit 3347fa0928210d96aaa2bd6cd5a8391d5e630873 upstream.
Workqueue is currently initialized in an early init call; however, there are cases where early boot code has to be split and reordered to come after workqueue initialization or the same code path which makes use of workqueues is used both before workqueue initailization and after. The latter cases have to gate workqueue usages with keventd_up() tests, which is nasty and easy to get wrong.
Workqueue usages have become widespread and it'd be a lot more convenient if it can be used very early from boot. This patch splits workqueue initialization into two steps. workqueue_init_early() which sets up the basic data structures so that workqueues can be created and work items queued, and workqueue_init() which actually brings up workqueues online and starts executing queued work items. The former step can be done very early during boot once memory allocation, cpumasks and idr are initialized. The latter right after kthreads become available.
This allows work item queueing and canceling from very early boot which is what most of these use cases want.
* As systemd_wq being initialized doesn't indicate that workqueue is fully online anymore, update keventd_up() to test wq_online instead. The follow-up patches will get rid of all its usages and the function itself.
* Flushing doesn't make sense before workqueue is fully initialized. The flush functions trigger WARN and return immediately before fully online.
* Work items are never in-flight before fully online. Canceling can always succeed by skipping the flush step.
* Some code paths can no longer assume to be called with irq enabled as irq is disabled during early boot. Use irqsave/restore operations instead.
v2: Watchdog init, which requires timer to be running, moved from
workqueue_init_early() to workqueue_init().
--- include/linux/workqueue.h | 7 +++- init/main.c | 10 ++++++ kernel/workqueue.c | 76 ++++++++++++++++++++++++++++++++++++---------- 3 files changed, 76 insertions(+), 17 deletions(-)
include/linux/workqueue.h +6 -1
@@ -359,6 +359,8 @@ extern struct workqueue_struct *system_fextern struct workqueue_struct *system_power_efficient_wq;extern struct workqueue_struct *system_freezable_power_efficient_wq; +extern bool wq_online; +extern struct workqueue_struct *__alloc_workqueue_key (const char *fmt,unsigned int flags,int max_active,struct lock_class_key *key,const char *lock_name, ...)__printf (1 ,6 );
@@ -598,7 +600,7 @@ static inline bool schedule_delayed_work*/ static inline bool keventd_up (void ) { -return system_wq !=NULL ; +return wq_online; }#ifndef CONFIG_SMP
@@ -635,4 +637,7 @@ int workqueue_online_cpu(unsigned int cpint workqueue_offline_cpu (unsigned int cpu);#endif +int __init workqueue_init_early (void ); +int __init workqueue_init (void ); +#endif
init/main.c +10 -0
@@ -554,6 +554,14 @@ asmlinkage __visible void __init start_k "Interrupts were enabled *very* early, fixing it\n"))local_irq_disable ();idr_init_cache (); + +/* +* Allow workqueue creation and work item queueing/cancelling +* early. Work item execution depends on kthreads and starts after +* workqueue_init(). +*/ +workqueue_init_early (); +rcu_init ();/* trace_printk() and trace points may be used after this */
@@ -1026,6 +1034,8 @@ static noinline void __init kernel_init_smp_prepare_cpus (setup_max_cpus); +workqueue_init (); +do_pre_smp_initcalls ();lockup_detector_init ();
kernel/workqueue.c +60 -16
143 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 141/264 random: defer fast pool mixing to worker
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 58340f8e952b613e0ead0bed58b97b05bf4743c5 upstream.
On PREEMPT_RT, it's problematic to take spinlocks from hard irq handlers. We can fix this by deferring to a workqueue the dumping of the fast pool into the input pool.
We accomplish this with some careful rules on fast_pool->count:
- When it's incremented to >= 64, we schedule the work.
- If the top bit is set, we never schedule the work, even if >= 64.
- The worker is responsible for setting it back to 0 when it's done.
There are two small issues around using workqueues for this purpose that we work around.
The first issue is that mix_interrupt_randomness() might be migrated to another CPU during CPU hotplug. This issue is rectified by checking that it hasn't been migrated (after disabling irqs). If it has been migrated, then we set the count to zero, so that when the CPU comes online again, it can requeue the work. As part of this, we switch to using an atomic_t, so that the increment in the irq handler doesn't wipe out the zeroing if the CPU comes back online while this worker is running.
The second issue is that, though relatively minor in effect, we probably want to make sure we get a consistent view of the pool onto the stack, in case it's interrupted by an irq while reading. To do this, we don't reenable irqs until after the copy. There are only 18 instructions between the cli and sti, so this is a pretty tiny window.
--- drivers/char/random.c | 63 ++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 49 insertions(+), 14 deletions(-)
drivers/char/random.c +49 -14
@@ -1174,9 +1174,10 @@ struct fast_pool {u32 pool32[4 ];u64 pool64[2 ]; }; +struct work_struct mix;unsigned long last; +atomic_t count;u16 reg_idx; -u8 count; };/*
@@ -1226,12 +1227,49 @@ static u32 get_reg(struct fast_pool *f,return *ptr; } +static void mix_interrupt_randomness (struct work_struct *work) +{ + struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix); +u32 pool[4 ]; + +/* Check to see if we're running on the wrong CPU due to hotplug. */ +local_irq_disable (); +if (fast_pool !=this_cpu_ptr (&irq_randomness)) { +local_irq_enable (); +/* +* If we are unlucky enough to have been moved to another CPU, +* during CPU hotplug while the CPU was shutdown then we set +* our count to zero atomically so that when the CPU comes +* back online, it can enqueue work again. The _release here +* pairs with the atomic_inc_return_acquire in +* add_interrupt_randomness(). +*/ +atomic_set_release (&fast_pool->count,0 ); +return ; + } + +/* +* Copy the pool to the stack so that the mixer always has a +* consistent view, before we reenable irqs again. +*/ +memcpy (pool, fast_pool->pool32,sizeof (pool)); +atomic_set (&fast_pool->count,0 ); + fast_pool->last = jiffies; +local_irq_enable (); + +mix_pool_bytes (pool,sizeof (pool)); +credit_entropy_bits (1 ); +memzero_explicit (pool,sizeof (pool)); +} +void add_interrupt_randomness (int irq) { +enum {MIX_INFLIGHT =1U <<31 };struct fast_pool *fast_pool =this_cpu_ptr (&irq_randomness);struct pt_regs *regs =get_irq_regs ();unsigned long now = jiffies;cycles_t cycles =random_get_entropy (); +unsigned int new_count;if (cycles ==0 ) cycles =get_reg (fast_pool, regs);
@@ -1251,12 +1289,13 @@ void add_interrupt_randomness(int irq) }fast_mix (fast_pool->pool32); - ++fast_pool->count; +/* The _acquire here pairs with the atomic_set_release in mix_interrupt_randomness(). */ + new_count = (unsigned int )atomic_inc_return_acquire (&fast_pool->count);if (unlikely (crng_init ==0 )) { -if (fast_pool->count >=64 && +if (new_count >=64 &&crng_fast_load (fast_pool->pool32,sizeof (fast_pool->pool32)) >0 ) { - fast_pool->count =0 ; +atomic_set (&fast_pool->count,0 ); fast_pool->last = now;if (spin_trylock (&input_pool.lock)) {_mix_pool_bytes (&fast_pool->pool32,sizeof (fast_pool->pool32));
@@ -1266,20 +1305,16 @@ void add_interrupt_randomness(int irq)return ; } -if ((fast_pool->count <64 ) && !time_after (now, fast_pool->last +HZ )) +if (new_count &MIX_INFLIGHT )return ; -if (!spin_trylock (&input_pool.lock)) +if (new_count <64 && !time_after (now, fast_pool->last +HZ ))return ; - fast_pool->last = now; -_mix_pool_bytes (&fast_pool->pool32,sizeof (fast_pool->pool32)); -spin_unlock (&input_pool.lock); - - fast_pool->count =0 ; - -/* Award one bit for the contents of the fast pool. */ -credit_entropy_bits (1 ); +if (unlikely (!fast_pool->mix.func)) +INIT_WORK (&fast_pool->mix, mix_interrupt_randomness); +atomic_or (MIX_INFLIGHT , &fast_pool->count); +queue_work_on (raw_smp_processor_id (), system_highpri_wq, &fast_pool->mix); }EXPORT_SYMBOL_GPL (add_interrupt_randomness);
Greg Kroah-Hartman
maintainerPATCH 142/264 random: do not take pool spinlock at boot
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit afba0b80b977b2a8f16234f2acd982f82710ba33 upstream.
Since rand_initialize() is run while interrupts are still off and nothing else is running, we don't need to repeatedly take and release the pool spinlock, especially in the RDSEED loop.
--- drivers/char/random.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/char/random.c +3 -3
@@ -974,10 +974,10 @@ int __init rand_initialize(void) rv =random_get_entropy (); arch_init = false; } -mix_pool_bytes (&rv,sizeof (rv)); +_mix_pool_bytes (&rv,sizeof (rv)); } -mix_pool_bytes (&now,sizeof (now)); -mix_pool_bytes (utsname (),sizeof (*(utsname ()))); +_mix_pool_bytes (&now,sizeof (now)); +_mix_pool_bytes (utsname (),sizeof (*(utsname ())));extract_entropy (base_crng.key,sizeof (base_crng.key)); ++base_crng.generation;
Greg Kroah-Hartman
maintainerPATCH 143/264 random: unify early init crng load accounting
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit da792c6d5f59a76c10a310c5d4c93428fd18f996 upstream.
crng_fast_load() and crng_slow_load() have different semantics:
- crng_fast_load() xors and accounts with crng_init_cnt.
- crng_slow_load() hashes and doesn't account.
However add_hwgenerator_randomness() can afford to hash (it's called from a kthread), and it should account. Additionally, ones that can afford to hash don't need to take a trylock but can take a normal lock. So, we combine these into one function, crng_pre_init_inject(), which allows us to control these in a uniform way. This will make it simpler later to simplify this all down when the time comes for that.
--- drivers/char/random.c | 114 +++++++++++++++++++++++++------------------------- 1 file changed, 59 insertions(+), 55 deletions(-)
drivers/char/random.c +59 -55
@@ -385,7 +385,7 @@ static void crng_make_state(u32 chacha_s* 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, because -* this is what crng_{fast,slow}_load mutate during early init. +* this is what crng_pre_init_inject() mutates during early init. */ if (unlikely (!crng_ready ())) {bool ready;
@@ -436,72 +436,75 @@ static void crng_make_state(u32 chacha_s }/* -* This function is for crng_init == 0 only. +* This function is for crng_init == 0 only. It loads entropy directly +* into the crng's key, without going through the input pool. It is, +* generally speaking, not very safe, but we use this only at early +* boot time when it's better to have something there rather than +* nothing. +* +* There are two paths, a slow one and a fast one. The slow one +* hashes the input along with the current key. The fast one simply +* xors it in, and should only be used from interrupt context. +* +* If account is set, then the crng_init_cnt counter is incremented. +* This shouldn't be set by functions like add_device_randomness(), +* where we can't trust the buffer passed to it is guaranteed to be +* unpredictable (so it might not have any entropy at all). * -* crng_fast_load() can be called by code in the interrupt service -* path. So we can't afford to dilly-dally. Returns the number of -* bytes processed from cp. +* Returns the number of bytes processed from input, which is bounded +* by CRNG_INIT_CNT_THRESH if account is true. */ -static size_t crng_fast_load (const void *cp,size_t len) +static size_t crng_pre_init_inject (const void *input,size_t len, +bool fast,bool account) {static int crng_init_cnt =0 ;unsigned long flags; -const u8 *src = (const u8 *)cp; -size_t ret =0 ; -if (!spin_trylock_irqsave (&base_crng.lock, flags)) -return 0 ; +if (fast) { +if (!spin_trylock_irqsave (&base_crng.lock, flags)) +return 0 ; + }else { +spin_lock_irqsave (&base_crng.lock, flags); + } +if (crng_init !=0 ) {spin_unlock_irqrestore (&base_crng.lock, flags);return 0 ; } -while (len >0 && crng_init_cnt <CRNG_INIT_CNT_THRESH ) { - base_crng.key[crng_init_cnt %sizeof (base_crng.key)] ^= *src; - src++; crng_init_cnt++; len--; ret++; - } -if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { - ++base_crng.generation; - crng_init =1 ; - } -spin_unlock_irqrestore (&base_crng.lock, flags); -if (crng_init ==1 ) -pr_notice ("fast init done\n" ); -return ret; -} -/* -* This function is for crng_init == 0 only. -* -* crng_slow_load() is called by add_device_randomness, which has two -* attributes. (1) We can't trust the buffer passed to it is -* guaranteed to be unpredictable (so it might not have any entropy at -* all), and (2) it doesn't have the performance constraints of -* crng_fast_load(). -* -* So, we simply hash the contents in with the current key. Finally, -* we do *not* advance crng_init_cnt since buffer we may get may be -* something like a fixed DMI table (for example), which might very -* well be unique to the machine, but is otherwise unvarying. -*/ -static void crng_slow_load (const void *cp,size_t len) -{ -unsigned long flags; -struct blake2s_state hash; +if (account) + len =min_t (size_t, len,CRNG_INIT_CNT_THRESH - crng_init_cnt); -blake2s_init (&hash,sizeof (base_crng.key)); - -if (!spin_trylock_irqsave (&base_crng.lock, flags)) -return ; -if (crng_init !=0 ) { -spin_unlock_irqrestore (&base_crng.lock, flags); -return ; +if (fast) { +const u8 *src = input; +size_t i; + +for (i =0 ; i < len; ++i) + base_crng.key[(crng_init_cnt + i) % +sizeof (base_crng.key)] ^= src[i]; + }else { +struct blake2s_state hash; + +blake2s_init (&hash,sizeof (base_crng.key)); +blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); +blake2s_update (&hash, input, len); +blake2s_final (&hash, base_crng.key); + } + +if (account) { + crng_init_cnt += len; +if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { + ++base_crng.generation; + crng_init =1 ; + } } -blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); -blake2s_update (&hash, cp, len); -blake2s_final (&hash, base_crng.key); -spin_unlock_irqrestore (&base_crng.lock, flags); + +if (crng_init ==1 ) +pr_notice ("fast init done\n" ); + +return len; }static void _get_random_bytes (void *buf,size_t nbytes)
@@ -1014,7 +1017,7 @@ void add_device_randomness(const void *bunsigned long flags;if (!crng_ready () && size) -crng_slow_load (buf, size); +crng_pre_init_inject (buf, size, false, false);spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (buf, size);
@@ -1131,7 +1134,7 @@ void add_hwgenerator_randomness(const vo size_t entropy) {if (unlikely (crng_init ==0 )) { -size_t ret =crng_fast_load (buffer, count); +size_t ret =crng_pre_init_inject (buffer, count, false, true);mix_pool_bytes (buffer, ret); count -= ret; buffer += ret;
@@ -1294,7 +1297,8 @@ void add_interrupt_randomness(int irq)if (unlikely (crng_init ==0 )) {if (new_count >=64 && -crng_fast_load (fast_pool->pool32,sizeof (fast_pool->pool32)) >0 ) { +crng_pre_init_inject (fast_pool->pool32,sizeof (fast_pool->pool32), + true, true) >0 ) {atomic_set (&fast_pool->count,0 ); fast_pool->last = now;if (spin_trylock (&input_pool.lock)) {
Greg Kroah-Hartman
maintainerPATCH 144/264 random: check for crng_init == 0 in add_device_randomness()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 1daf2f387652bf3a7044aea042f5023b3f6b189b upstream.
This has no real functional change, as crng_pre_init_inject() (and before that, crng_slow_init()) always checks for == 0, not >= 2. So correct the outer unlocked change to reflect that. Before this used crng_ready(), which was not correct.
--- drivers/char/random.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/char/random.c +1 -1
@@ -1016,7 +1016,7 @@ void add_device_randomness(const void *bunsigned long time =random_get_entropy () ^ jiffies;unsigned long flags; -if (!crng_ready () && size) +if (crng_init ==0 && size)crng_pre_init_inject (buf, size, false, false);spin_lock_irqsave (&input_pool.lock, flags);
Greg Kroah-Hartman
maintainerPATCH 145/264 hwrng: core - do not use multiple blank lines
In reply to Greg Kroah-HartmanFrom: Corentin LABBE <[email protected]>
commit 6bc17d90e62d16828d1a2113b54cfa4e04582fb6 upstream.
This patch fix the checkpatch warning "Please don't use multiple blank lines"
--- drivers/char/hw_random/core.c | 5 ----- 1 file changed, 5 deletions(-)
drivers/char/hw_random/core.c +0 -5
@@ -30,7 +30,6 @@*/ -#include <linux/device.h> #include <linux/hw_random.h> #include <linux/module.h>
@@ -45,12 +44,10 @@#include <linux/err.h> #include <asm/uaccess.h> -#define RNG_MODULE_NAME "hw_random"#define PFX RNG_MODULE_NAME ": "#define RNG_MISCDEV_MINOR 183/* official */ -static struct hwrng *current_rng;static struct task_struct *hwrng_fill;static LIST_HEAD (rng_list);
@@ -296,7 +293,6 @@ out_put: goto out; } -static const struct file_operations rng_chrdev_ops = { .owner =THIS_MODULE , .open = rng_dev_open,
@@ -314,7 +310,6 @@ static struct miscdevice rng_miscdev = { .groups = rng_dev_groups, }; -static ssize_t hwrng_attr_current_store (struct device *dev,struct device_attribute *attr,const char *buf,size_t len)
Greg Kroah-Hartman
maintainerPATCH 146/264 hwrng: core - rewrite better comparison to NULL
In reply to Greg Kroah-HartmanFrom: Corentin LABBE <[email protected]>
commit 2a971e3b248775f808950bdc0ac75f12a2853eff upstream.
This patch fix the checkpatch warning "Comparison to NULL could be written "!ptr"
--- drivers/char/hw_random/core.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/char/hw_random/core.c +1 -2
@@ -439,8 +439,7 @@ int hwrng_register(struct hwrng *rng)int err = -EINVAL ;struct hwrng *old_rng, *tmp; -if (rng->name ==NULL || - (rng->data_read ==NULL && rng->read ==NULL )) +if (!rng->name || (!rng->data_read && !rng->read)) goto out;mutex_lock (&rng_mutex);
Greg Kroah-Hartman
maintainerPATCH 147/264 hwrng: core - Rewrite the header
In reply to Greg Kroah-HartmanFrom: Corentin LABBE <[email protected]>
commit dd8014830d2b1fdf5328978ada706df3ec180c21 upstream.
checkpatch have lot of complaint about header. Furthermore, the header have some offtopic/useless information.
This patch rewrite a proper header.
--- drivers/char/hw_random/core.c | 38 +++++++++----------------------------- 1 file changed, 9 insertions(+), 29 deletions(-)
drivers/char/hw_random/core.c +9 -29
@@ -1,33 +1,13 @@/* -Added support for the AMD Geode LX RNG -(c) Copyright 2004-2005 Advanced Micro Devices, Inc. - -derived from - -Hardware driver for the Intel/AMD/VIA Random Number Generators (RNG) -(c) Copyright 2003 Red Hat Inc <[email protected]> - -derived from - -Hardware driver for the AMD 768 Random Number Generator (RNG) -(c) Copyright 2001 Red Hat Inc <[email protected]> - -derived from - -Hardware driver for Intel i810 Random Number Generator (RNG) -Copyright 2000,2001 Jeff Garzik <[email protected]> -Copyright 2000,2001 Philipp Rumpf <[email protected]> - -Added generic RNG API -Copyright 2006 Michael Buesch <[email protected]> -Copyright 2005 (c) MontaVista Software, Inc. - -Please read Documentation/hw_random.txt for details on use. - ----------------------------------------------------------- -This software may be used and distributed according to the terms -of the GNU General Public License, incorporated herein by reference. - +* hw_random/core.c: HWRNG core API +* +* Copyright 2006 Michael Buesch <[email protected]> +* Copyright 2005 (c) MontaVista Software, Inc. +* +* Please read Documentation/hw_random.txt for details on use. +* +* This software may be used and distributed according to the terms +* of the GNU General Public License, incorporated herein by reference. */ #include <linux/device.h>
Greg Kroah-Hartman
maintainerPATCH 148/264 hwrng: core - Move hwrng miscdev minor number to include/linux/miscdevice.h
In reply to Greg Kroah-HartmanFrom: Corentin LABBE <[email protected]>
commit fd50d71f94fb1c8614098949db068cd4c8dbb91d upstream.
This patch move the define for hwrng's miscdev minor number to include/linux/miscdevice.h.
It's better that all minor number are in the same place. Rename it to HWRNG_MINOR (from RNG_MISCDEV_MINOR) in he process since no other miscdev define have MISCDEV in their name.
--- drivers/char/hw_random/core.c | 3 +-- include/linux/miscdevice.h | 1 + 2 files changed, 2 insertions(+), 2 deletions(-)
drivers/char/hw_random/core.c +1 -2
@@ -26,7 +26,6 @@#define RNG_MODULE_NAME "hw_random"#define PFX RNG_MODULE_NAME ": " -#define RNG_MISCDEV_MINOR 183/* official */ static struct hwrng *current_rng;static struct task_struct *hwrng_fill;
@@ -283,7 +282,7 @@ static const struct file_operations rng_static const struct attribute_group *rng_dev_groups[];static struct miscdevice rng_miscdev = { - .minor =RNG_MISCDEV_MINOR , + .minor =HWRNG_MINOR , .name =RNG_MODULE_NAME , .nodename ="hwrng" , .fops = &rng_chrdev_ops,
include/linux/miscdevice.h +1 -0
@@ -31,6 +31,7 @@#define SGI_MMTIMER 153#define STORE_QUEUE_MINOR 155/* unused */ #define I2O_MINOR 166 +#define HWRNG_MINOR 183#define MICROCODE_MINOR 184#define VFIO_MINOR 196#define TUN_MINOR 200
Greg Kroah-Hartman
maintainerPATCH 149/264 hwrng: core - remove unused PFX macro
In reply to Greg Kroah-HartmanFrom: Corentin LABBE <[email protected]>
commit 079840bd13f793b915f6c8e44452eeb4a0aba8ba upstream.
This patch remove the unused PFX macro.
--- drivers/char/hw_random/core.c | 1 - 1 file changed, 1 deletion(-)
drivers/char/hw_random/core.c +0 -1
@@ -25,7 +25,6 @@#include <asm/uaccess.h> #define RNG_MODULE_NAME "hw_random" -#define PFX RNG_MODULE_NAME ": "static struct hwrng *current_rng;static struct task_struct *hwrng_fill;
Greg Kroah-Hartman
maintainerPATCH 150/264 hwrng: use rng source with best quality
In reply to Greg Kroah-HartmanFrom: Harald Freudenberger <[email protected]>
commit 2bbb6983887fefc8026beab01198d30f47b7bd22 upstream.
This patch rewoks the hwrng to always use the
rng source with best entropy quality.
On registation and unregistration the hwrng now tries to choose the best (= highest quality value) rng source. The handling of the internal list of registered rng sources is now always sorted by quality and the top most rng chosen.
--- drivers/char/hw_random/core.c | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-)
drivers/char/hw_random/core.c +19 -6
@@ -28,6 +28,7 @@static struct hwrng *current_rng;static struct task_struct *hwrng_fill; +/* list of registered rngs, sorted decending by quality */ static LIST_HEAD (rng_list);/* Protects rng_list and current_rng */ static DEFINE_MUTEX (rng_mutex);
@@ -416,6 +417,7 @@ int hwrng_register(struct hwrng *rng) {int err = -EINVAL ;struct hwrng *old_rng, *tmp; +struct list_head *rng_list_ptr;if (!rng->name || (!rng->data_read && !rng->read)) goto out;
@@ -431,14 +433,25 @@ int hwrng_register(struct hwrng *rng)init_completion (&rng->cleanup_done);complete (&rng->cleanup_done); +/* rng_list is sorted by decreasing quality */ +list_for_each (rng_list_ptr, &rng_list) { + tmp = list_entry(rng_list_ptr, struct hwrng, list); +if (tmp->quality < rng->quality) +break ; + } +list_add_tail (&rng->list, rng_list_ptr); + old_rng = current_rng; err =0 ; -if (!old_rng) { +if (!old_rng || (rng->quality > old_rng->quality)) { +/* +* Set new rng as current as the new rng source +* provides better entropy quality. +*/ err =set_current_rng (rng);if (err) goto out_unlock; } -list_add_tail (&rng->list, &rng_list);if (old_rng && !rng->init) {/*
@@ -465,12 +478,12 @@ void hwrng_unregister(struct hwrng *rng)list_del (&rng->list);if (current_rng == rng) {drop_current_rng (); +/* rng_list is sorted by quality, use the best (=first) one */ if (!list_empty (&rng_list)) { -struct hwrng *tail; - - tail = list_entry(rng_list.prev, struct hwrng, list); +struct hwrng *new_rng; -set_current_rng (tail); + new_rng = list_entry(rng_list.next, struct hwrng, list); +set_current_rng (new_rng); } }
Greg Kroah-Hartman
maintainerPATCH 151/264 hwrng: remember rng chosen by user
In reply to Greg Kroah-HartmanFrom: Harald Freudenberger <[email protected]>
commit 10a515ddb5f19a1ff0b9882c430b4427843169f3 upstream.
When a user chooses a rng source via sysfs attribute this rng should be sticky, even when other sources with better quality to register. This patch introduces a simple way to remember the user's choice. This is reflected by a new sysfs attribute file 'rng_selected' which shows if the current rng has been chosen by userspace. The new attribute file shows '1' for user selected rng and '0' otherwise.
--- drivers/char/hw_random/core.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-)
drivers/char/hw_random/core.c +19 -2
@@ -27,6 +27,8 @@#define RNG_MODULE_NAME "hw_random"static struct hwrng *current_rng; +/* the current rng has been explicitly chosen by user via sysfs */ +static int cur_rng_set_by_user;static struct task_struct *hwrng_fill;/* list of registered rngs, sorted decending by quality */ static LIST_HEAD (rng_list);
@@ -303,6 +305,7 @@ static ssize_t hwrng_attr_current_store(list_for_each_entry (rng, &rng_list, list) {if (sysfs_streq (rng->name, buf)) { err =0 ; + cur_rng_set_by_user =1 ;if (rng != current_rng) err =set_current_rng (rng);break ;
@@ -351,16 +354,27 @@ static ssize_t hwrng_attr_available_showreturn strlen (buf); } +static ssize_t hwrng_attr_selected_show (struct device *dev, +struct device_attribute *attr, +char *buf) +{ +return snprintf (buf,PAGE_SIZE ,"%d\n" , cur_rng_set_by_user); +} + static DEVICE_ATTR(rng_current, S_IRUGO | S_IWUSR, hwrng_attr_current_show, hwrng_attr_current_store); static DEVICE_ATTR(rng_available, S_IRUGO, hwrng_attr_available_show, NULL); +static DEVICE_ATTR(rng_selected, S_IRUGO, + hwrng_attr_selected_show, + NULL);static struct attribute *rng_dev_attrs[] = { &dev_attr_rng_current.attr, &dev_attr_rng_available.attr, + &dev_attr_rng_selected.attr,NULL };
@@ -443,10 +457,12 @@ int hwrng_register(struct hwrng *rng) old_rng = current_rng; err =0 ; -if (!old_rng || (rng->quality > old_rng->quality)) { +if (!old_rng || + (!cur_rng_set_by_user && rng->quality > old_rng->quality)) {/* * Set new rng as current as the new rng source -* provides better entropy quality. +* provides better entropy quality and was not +* chosen by userspace. */ err =set_current_rng (rng);if (err)
@@ -478,6 +494,7 @@ void hwrng_unregister(struct hwrng *rng)list_del (&rng->list);if (current_rng == rng) {drop_current_rng (); + cur_rng_set_by_user =0 ;/* rng_list is sorted by quality, use the best (=first) one */ if (!list_empty (&rng_list)) {struct hwrng *new_rng;
Greg Kroah-Hartman
maintainerPATCH 152/264 random: pull add_hwgenerator_randomness() declaration into random.h
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit b777c38239fec5a528e59f55b379e31b1a187524 upstream.
add_hwgenerator_randomness() is a function implemented and documented inside of random.c. It is the way that hardware RNGs push data into it. Therefore, it should be declared in random.h. Otherwise sparse complains with:
random.c:1137:6: warning: symbol 'add_hwgenerator_randomness' was not declared. Should it be static?
The alternative would be to include hw_random.h into random.c, but that wouldn't really be good for anything except slowing down compile time.
--- drivers/char/hw_random/core.c | 1 + include/linux/hw_random.h | 2 -- include/linux/random.h | 2 ++ 3 files changed, 3 insertions(+), 2 deletions(-)
drivers/char/hw_random/core.c +1 -0
@@ -12,6 +12,7 @@#include <linux/device.h> #include <linux/hw_random.h> +#include <linux/random.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h>
include/linux/hw_random.h +0 -2
@@ -60,7 +60,5 @@ extern int devm_hwrng_register(struct de/** Unregister a Hardware Random Number Generator driver. */ extern void hwrng_unregister (struct hwrng *rng);extern void devm_hwrng_unregister (struct device *dve,struct hwrng *rng); -/** Feed random bits into the pool. */ -extern void add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy);#endif /* LINUX_HWRANDOM_H_ */
include/linux/random.h +2 -0
@@ -32,6 +32,8 @@ static inline void add_latent_entropy(vo extern void add_input_randomness(unsigned int type, unsigned int code, unsigned int value) __latent_entropy; extern void add_interrupt_randomness(int irq) __latent_entropy; +extern void add_hwgenerator_randomness (const void *buffer,size_t count, +size_t entropy);extern void get_random_bytes (void *buf,size_t nbytes);extern int wait_for_random_bytes (void );
Greg Kroah-Hartman
maintainerPATCH 153/264 random: clear fast pool, crng, and batches in cpuhp bring up
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 3191dd5a1179ef0fad5a050a1702ae98b6251e8f upstream.
For the irq randomness fast pool, rather than having to use expensive atomics, which were visibly the most expensive thing in the entire irq handler, simply take care of the extreme edge case of resetting count to zero in the cpuhp online handler, just after workqueues have been reenabled. This simplifies the code a bit and lets us use vanilla variables rather than atomics, and performance should be improved.
As well, very early on when the CPU comes up, while interrupts are still disabled, we clear out the per-cpu crng and its batches, so that it always starts with fresh randomness.
--- drivers/char/random.c | 62 ++++++++++++++++++++++++++++++++++----------- include/linux/cpuhotplug.h | 2 + include/linux/random.h | 5 +++ kernel/cpu.c | 11 +++++++ 4 files changed, 65 insertions(+), 15 deletions(-)
drivers/char/random.c +47 -15
@@ -694,6 +694,25 @@ u32 get_random_u32(void) }EXPORT_SYMBOL (get_random_u32); +#ifdef CONFIG_SMP +/* +* This function is called when the CPU is coming up, with entry +* CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP. +*/ +int random_prepare_cpu (unsigned int cpu) +{ +/* +* When the cpu comes back online, immediately invalidate both +* the per-cpu crng and all batches, so that we serve fresh +* randomness. +*/ +per_cpu_ptr (&crngs, cpu)->generation =ULONG_MAX ; +per_cpu_ptr (&batched_entropy_u32, cpu)->position =UINT_MAX ; +per_cpu_ptr (&batched_entropy_u64, cpu)->position =UINT_MAX ; +return 0 ; +} +#endif +/** * randomize_page - Generate a random, page aligned address * @start: The smallest acceptable address the caller will take.
@@ -1179,7 +1198,7 @@ struct fast_pool { };struct work_struct mix;unsigned long last; -atomic_t count; +unsigned int count;u16 reg_idx; };
@@ -1215,6 +1234,29 @@ static void fast_mix(u32 pool[4]) static DEFINE_PER_CPU(struct fast_pool, irq_randomness); +#ifdef CONFIG_SMP +/* +* This function is called when the CPU has just come online, with +* entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE. +*/ +int random_online_cpu (unsigned int cpu) +{ +/* +* During CPU shutdown and before CPU onlining, add_interrupt_ +* randomness() may schedule mix_interrupt_randomness(), and +* set the MIX_INFLIGHT flag. However, because the worker can +* be scheduled on a different CPU during this period, that +* flag will never be cleared. For that reason, we zero out +* the flag here, which runs just after workqueues are onlined +* for the CPU again. This also has the effect of setting the +* irq randomness count to zero so that new accumulated irqs +* are fresh. +*/ +per_cpu_ptr (&irq_randomness, cpu)->count =0 ; +return 0 ; +} +#endif +static u32 get_reg (struct fast_pool *f,struct pt_regs *regs) {u32 *ptr = (u32 *)regs;
@@ -1239,15 +1281,6 @@ static void mix_interrupt_randomness(strlocal_irq_disable ();if (fast_pool !=this_cpu_ptr (&irq_randomness)) {local_irq_enable (); -/* -* If we are unlucky enough to have been moved to another CPU, -* during CPU hotplug while the CPU was shutdown then we set -* our count to zero atomically so that when the CPU comes -* back online, it can enqueue work again. The _release here -* pairs with the atomic_inc_return_acquire in -* add_interrupt_randomness(). -*/ -atomic_set_release (&fast_pool->count,0 );return ; }
@@ -1256,7 +1289,7 @@ static void mix_interrupt_randomness(str* consistent view, before we reenable irqs again. */ memcpy (pool, fast_pool->pool32,sizeof (pool)); -atomic_set (&fast_pool->count,0 ); + fast_pool->count =0 ; fast_pool->last = jiffies;local_irq_enable ();
@@ -1292,14 +1325,13 @@ void add_interrupt_randomness(int irq) }fast_mix (fast_pool->pool32); -/* The _acquire here pairs with the atomic_set_release in mix_interrupt_randomness(). */ - new_count = (unsigned int )atomic_inc_return_acquire (&fast_pool->count); + new_count = ++fast_pool->count;if (unlikely (crng_init ==0 )) {if (new_count >=64 &&crng_pre_init_inject (fast_pool->pool32,sizeof (fast_pool->pool32), true, true) >0 ) { -atomic_set (&fast_pool->count,0 ); + fast_pool->count =0 ; fast_pool->last = now;if (spin_trylock (&input_pool.lock)) {_mix_pool_bytes (&fast_pool->pool32,sizeof (fast_pool->pool32));
@@ -1317,7 +1349,7 @@ void add_interrupt_randomness(int irq)if (unlikely (!fast_pool->mix.func))INIT_WORK (&fast_pool->mix, mix_interrupt_randomness); -atomic_or (MIX_INFLIGHT , &fast_pool->count); + fast_pool->count |=MIX_INFLIGHT ;queue_work_on (raw_smp_processor_id (), system_highpri_wq, &fast_pool->mix); }EXPORT_SYMBOL_GPL (add_interrupt_randomness);
include/linux/cpuhotplug.h +2 -0
@@ -29,6 +29,7 @@ enum cpuhp_state {CPUHP_ACPI_CPUDRV_DEAD ,CPUHP_S390_PFAULT_DEAD ,CPUHP_BLK_MQ_DEAD , +CPUHP_RANDOM_PREPARE ,CPUHP_WORKQUEUE_PREP ,CPUHP_POWER_NUMA_PREPARE , CPUHP_HRTIMERS_PREPARE,
@@ -119,6 +120,7 @@ enum cpuhp_state {CPUHP_AP_PERF_ARM_CCN_ONLINE ,CPUHP_AP_PERF_ARM_L2X0_ONLINE ,CPUHP_AP_WORKQUEUE_ONLINE , +CPUHP_AP_RANDOM_ONLINE ,CPUHP_AP_RCUTREE_ONLINE ,CPUHP_AP_NOTIFY_ONLINE , CPUHP_AP_ONLINE_DYN,
include/linux/random.h +5 -0
@@ -135,4 +135,9 @@ static inline bool __init arch_get_rando }#endif +#ifdef CONFIG_SMP +extern int random_prepare_cpu (unsigned int cpu); +extern int random_online_cpu (unsigned int cpu); +#endif +#endif /* _LINUX_RANDOM_H */
kernel/cpu.c +11 -0
@@ -26,6 +26,7 @@#include <linux/smpboot.h> #include <linux/relay.h> #include <linux/slab.h> +#include <linux/random.h> #include <trace/events/power.h> #define CREATE_TRACE_POINTS
@@ -1404,6 +1405,11 @@ static struct cpuhp_step cpuhp_bp_states .startup.single = perf_event_init_cpu, .teardown.single = perf_event_exit_cpu, }, + [CPUHP_RANDOM_PREPARE] = { + .name = "random:prepare", + .startup.single = random_prepare_cpu, + .teardown.single = NULL, + }, [CPUHP_WORKQUEUE_PREP] = { .name = "workqueue:prepare", .startup.single = workqueue_prepare_cpu,
@@ -1529,6 +1535,11 @@ static struct cpuhp_step cpuhp_ap_states .startup.single = workqueue_online_cpu, .teardown.single = workqueue_offline_cpu, }, + [CPUHP_AP_RANDOM_ONLINE] = { + .name = "random:online", + .startup.single = random_online_cpu, + .teardown.single = NULL, + }, [CPUHP_AP_RCUTREE_ONLINE] = { .name = "RCU/tree:online", .startup.single = rcutree_online_cpu,
Greg Kroah-Hartman
maintainerPATCH 154/264 random: round-robin registers as ulong, not u32
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit da3951ebdcd1cb1d5c750e08cd05aee7b0c04d9a upstream.
When the interrupt handler does not have a valid cycle counter, it calls get_reg() to read a register from the irq stack, in round-robin. Currently it does this assuming that registers are 32-bit. This is _probably_ the case, and probably all platforms without cycle counters are in fact 32-bit platforms. But maybe not, and either way, it's not quite correct. This commit fixes that to deal with unsigned long rather than u32.
--- drivers/char/random.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/char/random.c +3 -3
@@ -1257,15 +1257,15 @@ int random_online_cpu(unsigned int cpu) }#endif -static u32 get_reg (struct fast_pool *f,struct pt_regs *regs) +static unsigned long get_reg (struct fast_pool *f,struct pt_regs *regs) { -u32 *ptr = (u32 *)regs; +unsigned long *ptr = (unsigned long *)regs;unsigned int idx;if (regs ==NULL )return 0 ; idx =READ_ONCE (f->reg_idx); -if (idx >=sizeof (struct pt_regs ) /sizeof (u32)) +if (idx >=sizeof (struct pt_regs ) /sizeof (unsigned long )) idx =0 ; ptr += idx++;WRITE_ONCE (f->reg_idx, idx);
Greg Kroah-Hartman
maintainerPATCH 155/264 random: only wake up writers after zap if threshold was passed
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a3f9e8910e1584d7725ef7d5ac870920d42d0bb4 upstream.
The only time that we need to wake up /dev/random writers on RNDCLEARPOOL/RNDZAPPOOL is when we're changing from a value that is greater than or equal to POOL_MIN_BITS to zero, because if we're changing from below POOL_MIN_BITS to zero, the writers are already unblocked.
--- drivers/char/random.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/char/random.c +1 -1
@@ -1578,7 +1578,7 @@ static long random_ioctl(struct file *f,*/ if (!capable (CAP_SYS_ADMIN ))return -EPERM ; -if (xchg (&input_pool.entropy_count,0 )) { +if (xchg (&input_pool.entropy_count,0 ) >=POOL_MIN_BITS ) {wake_up_interruptible (&random_write_wait);kill_fasync (&fasync,SIGIO ,POLL_OUT ); }
Greg Kroah-Hartman
maintainerPATCH 156/264 random: cleanup UUID handling
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 64276a9939ff414f2f0db38036cf4e1a0a703394 upstream.
Rather than hard coding various lengths, we can use the right constants. Strings should be char * while buffers should be u8 *. Rather than have a nonsensical and unused maxlength, just remove it. Finally, use snprintf instead of sprintf, just out of good hygiene.
As well, remove the old comment about returning a binary UUID via the binary sysctl syscall. That syscall was removed from the kernel in 5.5, and actually, the "uuid_strategy" function and related infrastructure for even serving it via the binary sysctl syscall was removed with 894d2491153a ("sysctl drivers: Remove dead binary sysctl support") back in 2.6.33.
--- drivers/char/random.c | 29 +++++++++++++---------------- include/linux/uuid.h | 1 + 2 files changed, 14 insertions(+), 16 deletions(-)
drivers/char/random.c +13 -16
@@ -1655,22 +1655,25 @@ const struct file_operations urandom_fopstatic int sysctl_random_min_urandom_seed =60 ;static int sysctl_random_write_wakeup_bits =POOL_MIN_BITS ;static int sysctl_poolsize =POOL_BITS ; -static char sysctl_bootid[16 ]; +static u8 sysctl_bootid[UUID_SIZE ];/* * This function is used to return both the bootid UUID, and random -* UUID. The difference is in whether table->data is NULL; if it is, +* UUID. The difference is in whether table->data is NULL; if it is, * then a new UUID is generated and returned to the user. -* -* If the user accesses this via the proc interface, the UUID will be -* returned as an ASCII string in the standard UUID format; if via the -* sysctl system call, as 16 bytes of binary data. */ static int proc_do_uuid (struct ctl_table *table,int write,void __user *buffer,size_t *lenp,loff_t *ppos) { -struct ctl_table fake_table; -unsigned char buf[64 ], tmp_uuid[16 ], *uuid; +u8 tmp_uuid[UUID_SIZE ], *uuid; +char uuid_string[UUID_STRING_LEN +1 ]; +struct ctl_table fake_table = { + .data = uuid_string, + .maxlen =UUID_STRING_LEN + }; + +if (write) +return -EPERM ; uuid = table->data;if (!uuid) {
@@ -1685,12 +1688,8 @@ static int proc_do_uuid(struct ctl_tablespin_unlock (&bootid_spinlock); } -sprintf (buf,"%pU" , uuid); - - fake_table.data = buf; - fake_table.maxlen =sizeof (buf); - -return proc_dostring (&fake_table, write, buffer, lenp, ppos); +snprintf (uuid_string,sizeof (uuid_string),"%pU" , uuid); +return proc_dostring (&fake_table,0 , buffer, lenp, ppos); }extern struct ctl_table random_table[];
@@ -1726,13 +1725,11 @@ struct ctl_table random_table[] = { { .procname = "boot_id", .data = &sysctl_bootid, - .maxlen = 16, .mode = 0444, .proc_handler = proc_do_uuid, }, { .procname = "uuid", - .maxlen = 16, .mode = 0444, .proc_handler = proc_do_uuid, },
include/linux/uuid.h +1 -0
@@ -23,6 +23,7 @@* not including trailing NUL. */ #define UUID_STRING_LEN 36 +#define UUID_SIZE 16static inline int uuid_le_cmp (const uuid_le u1,const uuid_le u2) {
Greg Kroah-Hartman
maintainerPATCH 157/264 random: unify cycles_t and jiffies usage and types
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit abded93ec1e9692920fe309f07f40bd1035f2940 upstream.
random_get_entropy() returns a cycles_t, not an unsigned long, which is sometimes 64 bits on various 32-bit platforms, including x86. Conversely, jiffies is always unsigned long. This commit fixes things to use cycles_t for fields that use random_get_entropy(), named "cycles", and unsigned long for fields that use jiffies, named "now". It's also good to mix in a cycles_t and a jiffies in the same way for both add_device_randomness and add_timer_randomness, rather than using xor in one case. Finally, we unify the order of these volatile reads, always reading the more precise cycles counter, and then jiffies, so that the cycle counter is as close to the event as possible.
--- drivers/char/random.c | 56 ++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 29 deletions(-)
drivers/char/random.c +27 -29
@@ -1016,12 +1016,6 @@ int __init rand_initialize(void)return 0 ; } -/* There is one of these per entropy source */ -struct timer_rand_state { -cycles_t last_time; -long last_delta, last_delta2; -}; -/* * Add device- or boot-specific data to the input pool to help * initialize it.
@@ -1032,19 +1026,26 @@ struct timer_rand_state {*/ void add_device_randomness (const void *buf,size_t size) { -unsigned long time =random_get_entropy () ^ jiffies; -unsigned long flags; +cycles_t cycles =random_get_entropy (); +unsigned long flags, now = jiffies;if (crng_init ==0 && size)crng_pre_init_inject (buf, size, false, false);spin_lock_irqsave (&input_pool.lock, flags); +_mix_pool_bytes (&cycles,sizeof (cycles)); +_mix_pool_bytes (&now,sizeof (now));_mix_pool_bytes (buf, size); -_mix_pool_bytes (&time,sizeof (time));spin_unlock_irqrestore (&input_pool.lock, flags); }EXPORT_SYMBOL (add_device_randomness); +/* There is one of these per entropy source */ +struct timer_rand_state { +unsigned long last_time; +long last_delta, last_delta2; +}; +/* * This function adds entropy to the entropy "pool" by using timing * delays. It uses the timer_rand_state structure to make an estimate
@@ -1053,29 +1054,26 @@ EXPORT_SYMBOL(add_device_randomness);* The number "num" is also added to the pool - it should somehow describe * the type of event which just happened. This is currently 0-255 for * keyboard scan codes, and 256 upwards for interrupts. -* */ static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) { -struct { -long jiffies; -unsigned int cycles; -unsigned int num; - } sample; +cycles_t cycles =random_get_entropy (); +unsigned long flags, now = jiffies;long delta, delta2, delta3; - sample.jiffies = jiffies; - sample.cycles =random_get_entropy (); - sample.num = num; -mix_pool_bytes (&sample,sizeof (sample)); +spin_lock_irqsave (&input_pool.lock, flags); +_mix_pool_bytes (&cycles,sizeof (cycles)); +_mix_pool_bytes (&now,sizeof (now)); +_mix_pool_bytes (&num,sizeof (num)); +spin_unlock_irqrestore (&input_pool.lock, flags);/* * Calculate number of bits of randomness we probably added. * We take into account the first, second and third-order deltas * in order to make our estimate. */ - delta = sample.jiffies - state->last_time; - state->last_time = sample.jiffies; + delta = now -READ_ONCE (state->last_time); +WRITE_ONCE (state->last_time, now); delta2 = delta - state->last_delta; state->last_delta = delta;
@@ -1301,10 +1299,10 @@ static void mix_interrupt_randomness(strvoid add_interrupt_randomness (int irq) {enum {MIX_INFLIGHT =1U <<31 }; +cycles_t cycles =random_get_entropy (); +unsigned long now = jiffies;struct fast_pool *fast_pool =this_cpu_ptr (&irq_randomness);struct pt_regs *regs =get_irq_regs (); -unsigned long now = jiffies; -cycles_t cycles =random_get_entropy ();unsigned int new_count;if (cycles ==0 )
@@ -1379,28 +1377,28 @@ static void entropy_timer(unsigned longstatic void try_to_generate_entropy (void ) {struct { -unsigned long now; +cycles_t cycles;struct timer_list timer; } stack; - stack.now =random_get_entropy (); + stack.cycles =random_get_entropy ();/* Slow counter - or none. Don't even bother */ -if (stack.now ==random_get_entropy ()) +if (stack.cycles ==random_get_entropy ())return ;__setup_timer_on_stack (&stack.timer, entropy_timer,0 ,0 );while (!crng_ready ()) {if (!timer_pending (&stack.timer))mod_timer (&stack.timer, jiffies +1 ); -mix_pool_bytes (&stack.now,sizeof (stack.now)); +mix_pool_bytes (&stack.cycles,sizeof (stack.cycles));schedule (); - stack.now =random_get_entropy (); + stack.cycles =random_get_entropy (); }del_timer_sync (&stack.timer);destroy_timer_on_stack (&stack.timer); -mix_pool_bytes (&stack.now,sizeof (stack.now)); +mix_pool_bytes (&stack.cycles,sizeof (stack.cycles)); }
Greg Kroah-Hartman
maintainerPATCH 158/264 random: do crng pre-init loading in worker rather than irq
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit c2a7de4feb6e09f23af7accc0f882a8fa92e7ae5 upstream.
Taking spinlocks from IRQ context is generally problematic for PREEMPT_RT. That is, in part, why we take trylocks instead. However, a spin_try_lock() is also problematic since another spin_lock() invocation can potentially PI-boost the wrong task, as the spin_try_lock() is invoked from an IRQ-context, so the task on CPU (random task or idle) is not the actual owner.
Additionally, by deferring the crng pre-init loading to the worker, we can use the cryptographic hash function rather than xor, which is perhaps a meaningful difference when considering this data has only been through the relatively weak fast_mix() function.
The biggest downside of this approach is that the pre-init loading is now deferred until later, which means things that need random numbers after interrupts are enabled, but before workqueues are running -- or before this particular worker manages to run -- are going to get into trouble. Hopefully in the real world, this window is rather small, especially since this code won't run until 64 interrupts had occurred.
--- drivers/char/random.c | 65 ++++++++++++++------------------------------------ 1 file changed, 19 insertions(+), 46 deletions(-)
drivers/char/random.c +19 -46
@@ -442,10 +442,6 @@ static void crng_make_state(u32 chacha_s* boot time when it's better to have something there rather than * nothing. * -* There are two paths, a slow one and a fast one. The slow one -* hashes the input along with the current key. The fast one simply -* xors it in, and should only be used from interrupt context. -* * If account is set, then the crng_init_cnt counter is incremented. * This shouldn't be set by functions like add_device_randomness(), * where we can't trust the buffer passed to it is guaranteed to be
@@ -454,19 +450,15 @@ static void crng_make_state(u32 chacha_s* Returns the number of bytes processed from input, which is bounded * by CRNG_INIT_CNT_THRESH if account is true. */ -static size_t crng_pre_init_inject (const void *input,size_t len, -bool fast,bool account) +static size_t crng_pre_init_inject (const void *input,size_t len,bool account) {static int crng_init_cnt =0 ; +struct blake2s_state hash;unsigned long flags; -if (fast) { -if (!spin_trylock_irqsave (&base_crng.lock, flags)) -return 0 ; - }else { -spin_lock_irqsave (&base_crng.lock, flags); - } +blake2s_init (&hash,sizeof (base_crng.key)); +spin_lock_irqsave (&base_crng.lock, flags);if (crng_init !=0 ) {spin_unlock_irqrestore (&base_crng.lock, flags);return 0 ;
@@ -475,21 +467,9 @@ static size_t crng_pre_init_inject(constif (account) len =min_t (size_t, len,CRNG_INIT_CNT_THRESH - crng_init_cnt); -if (fast) { -const u8 *src = input; -size_t i; - -for (i =0 ; i < len; ++i) - base_crng.key[(crng_init_cnt + i) % -sizeof (base_crng.key)] ^= src[i]; - }else { -struct blake2s_state hash; - -blake2s_init (&hash,sizeof (base_crng.key)); -blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); -blake2s_update (&hash, input, len); -blake2s_final (&hash, base_crng.key); - } +blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); +blake2s_update (&hash, input, len); +blake2s_final (&hash, base_crng.key);if (account) { crng_init_cnt += len;
@@ -1030,7 +1010,7 @@ void add_device_randomness(const void *bunsigned long flags, now = jiffies;if (crng_init ==0 && size) -crng_pre_init_inject (buf, size, false, false); +crng_pre_init_inject (buf, size, false);spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (&cycles,sizeof (cycles));
@@ -1151,7 +1131,7 @@ void add_hwgenerator_randomness(const vo size_t entropy) {if (unlikely (crng_init ==0 )) { -size_t ret =crng_pre_init_inject (buffer, count, false, true); +size_t ret =crng_pre_init_inject (buffer, count, true);mix_pool_bytes (buffer, ret); count -= ret; buffer += ret;
@@ -1291,8 +1271,14 @@ static void mix_interrupt_randomness(str fast_pool->last = jiffies;local_irq_enable (); -mix_pool_bytes (pool,sizeof (pool)); -credit_entropy_bits (1 ); +if (unlikely (crng_init ==0 )) { +crng_pre_init_inject (pool,sizeof (pool), true); +mix_pool_bytes (pool,sizeof (pool)); + }else { +mix_pool_bytes (pool,sizeof (pool)); +credit_entropy_bits (1 ); + } +memzero_explicit (pool,sizeof (pool)); }
@@ -1325,24 +1311,11 @@ void add_interrupt_randomness(int irq)fast_mix (fast_pool->pool32); new_count = ++fast_pool->count; -if (unlikely (crng_init ==0 )) { -if (new_count >=64 && -crng_pre_init_inject (fast_pool->pool32,sizeof (fast_pool->pool32), - true, true) >0 ) { - fast_pool->count =0 ; - fast_pool->last = now; -if (spin_trylock (&input_pool.lock)) { -_mix_pool_bytes (&fast_pool->pool32,sizeof (fast_pool->pool32)); -spin_unlock (&input_pool.lock); - } - } -return ; - } -if (new_count &MIX_INFLIGHT )return ; -if (new_count <64 && !time_after (now, fast_pool->last +HZ )) +if (new_count <64 && (!time_after (now, fast_pool->last +HZ ) || +unlikely (crng_init ==0 )))return ;if (unlikely (!fast_pool->mix.func))
Greg Kroah-Hartman
maintainerPATCH 159/264 random: give sysctl_random_min_urandom_seed a more sensible value
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit d0efdf35a6a71d307a250199af6fce122a7c7e11 upstream.
This isn't used by anything or anywhere, but we can't delete it due to compatibility. So at least give it the correct value of what it's supposed to be instead of a garbage one.
--- drivers/char/random.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/char/random.c +2 -2
@@ -1613,7 +1613,7 @@ const struct file_operations urandom_fop* to avoid breaking old userspaces, but writing to it does not * change any behavior of the RNG. * -* - urandom_min_reseed_secs - fixed to the meaningless value "60". +* - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL. * It is writable to avoid breaking old userspaces, but writing * to it does not change any behavior of the RNG. *
@@ -1623,7 +1623,7 @@ const struct file_operations urandom_fop#include <linux/sysctl.h> -static int sysctl_random_min_urandom_seed =60 ; +static int sysctl_random_min_urandom_seed =CRNG_RESEED_INTERVAL /HZ ;static int sysctl_random_write_wakeup_bits =POOL_MIN_BITS ;static int sysctl_poolsize =POOL_BITS ;static u8 sysctl_bootid[UUID_SIZE ];
Greg Kroah-Hartman
maintainerPATCH 160/264 random: dont let 644 read-only sysctls be written to
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 77553cf8f44863b31da242cf24671d76ddb61597 upstream.
We leave around these old sysctls for compatibility, and we keep them "writable" for compatibility, but even after writing, we should keep reporting the same value. This is consistent with how userspaces tend to use sysctl_random_write_wakeup_bits, writing to it, and then later reading from it and using the value.
--- drivers/char/random.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/char/random.c +9 -2
@@ -1663,6 +1663,13 @@ static int proc_do_uuid(struct ctl_tablereturn proc_dostring (&fake_table,0 , buffer, lenp, ppos); } +/* The same as proc_dointvec, but writes don't change anything. */ +static int proc_do_rointvec (struct ctl_table *table,int write,void __user *buffer, +size_t *lenp,loff_t *ppos) +{ +return write ?0 :proc_dointvec (table,0 , buffer, lenp, ppos); +} +extern struct ctl_table random_table[];struct ctl_table random_table[] = { {
@@ -1684,14 +1691,14 @@ struct ctl_table random_table[] = { .data = &sysctl_random_write_wakeup_bits, .maxlen = sizeof(int), .mode = 0644, - .proc_handler = proc_dointvec, + .proc_handler = proc_do_rointvec, }, { .procname = "urandom_min_reseed_secs", .data = &sysctl_random_min_urandom_seed, .maxlen = sizeof(int), .mode = 0644, - .proc_handler = proc_dointvec, + .proc_handler = proc_do_rointvec, }, { .procname = "boot_id",
Greg Kroah-Hartman
maintainerPATCH 161/264 random: replace custom notifier chain with standard one
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 5acd35487dc911541672b3ffc322851769c32a56 upstream.
We previously rolled our own randomness readiness notifier, which only has two users in the whole kernel. Replace this with a more standard atomic notifier block that serves the same purpose with less code. Also unexport the symbols, because no modules use it, only unconditional builtins. The only drawback is that it's possible for a notification handler returning the "stop" code to prevent further processing, but given that there are only two users, and that we're unexporting this anyway, that doesn't seem like a significant drawback for the simplification we receive here.
--- crypto/drbg.c | 17 +++++------- drivers/char/random.c | 69 ++++++++++++++----------------------------------- include/crypto/drbg.h | 2 - include/linux/random.h | 10 ++----- lib/random32.c | 13 +++++---- 5 files changed, 41 insertions(+), 70 deletions(-)
crypto/drbg.c +8 -9
@@ -1390,12 +1390,13 @@ static int drbg_generate_long(struct drbreturn 0 ; } -static void drbg_schedule_async_seed (struct random_ready_callback *rdy) +static int drbg_schedule_async_seed (struct notifier_block *nb,unsigned long action,void *data) { - struct drbg_state *drbg = container_of(rdy, struct drbg_state, + struct drbg_state *drbg = container_of(nb, struct drbg_state, random_ready);schedule_work (&drbg->seed_work); +return 0 ; }static int drbg_prepare_hrng (struct drbg_state *drbg)
@@ -1408,10 +1409,8 @@ static int drbg_prepare_hrng(struct drbgINIT_WORK (&drbg->seed_work, drbg_async_seed); - drbg->random_ready.owner =THIS_MODULE ; - drbg->random_ready.func = drbg_schedule_async_seed; - - err =add_random_ready_callback (&drbg->random_ready); + drbg->random_ready.notifier_call = drbg_schedule_async_seed; + err =register_random_ready_notifier (&drbg->random_ready);switch (err) {case 0 :
@@ -1422,7 +1421,7 @@ static int drbg_prepare_hrng(struct drbg/* fall through */ default : - drbg->random_ready.func =NULL ; + drbg->random_ready.notifier_call =NULL ;return err; }
@@ -1528,8 +1527,8 @@ free_everything:*/ static int drbg_uninstantiate (struct drbg_state *drbg) { -if (drbg->random_ready.func) { -del_random_ready_callback (&drbg->random_ready); +if (drbg->random_ready.notifier_call) { +unregister_random_ready_notifier (&drbg->random_ready);cancel_work_sync (&drbg->seed_work);crypto_free_rng (drbg->jent); drbg->jent =NULL ;
drivers/char/random.c +21 -48
101 lines not on this page · raw message
include/crypto/drbg.h +1 -1
@@ -136,7 +136,7 @@ struct drbg_state {const struct drbg_state_ops *d_ops;const struct drbg_core *core;struct drbg_string test_data; -struct random_ready_callback random_ready; +struct notifier_block random_ready; };static inline __u8 drbg_statelen (struct drbg_state *drbg)
include/linux/random.h +3 -7
@@ -10,11 +10,7 @@#include <uapi/linux/random.h> -struct random_ready_callback { -struct list_head list; -void (*func)(struct random_ready_callback *rdy); -struct module *owner; -}; +struct notifier_block ;extern void add_device_randomness (const void *,size_t );extern void add_bootloader_randomness (const void *,size_t );
@@ -39,8 +35,8 @@ extern void get_random_bytes(void *buf,extern int wait_for_random_bytes (void );extern int __init rand_initialize (void );extern bool rng_is_initialized (void ); -extern int add_random_ready_callback (struct random_ready_callback *rdy); -extern void del_random_ready_callback (struct random_ready_callback *rdy); +extern int register_random_ready_notifier (struct notifier_block *nb); +extern int unregister_random_ready_notifier (struct notifier_block *nb);extern size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes);#ifndef MODULE
lib/random32.c +8 -5
@@ -39,6 +39,7 @@#include <linux/sched.h> #include <linux/bitops.h> #include <linux/slab.h> +#include <linux/notifier.h> #include <asm/unaligned.h> /**
@@ -545,9 +546,11 @@ static void prandom_reseed(unsigned long* To avoid worrying about whether it's safe to delay that interrupt * long enough to seed all CPUs, just schedule an immediate timer event. */ -static void prandom_timer_start (struct random_ready_callback *unused) +static int prandom_timer_start (struct notifier_block *nb, +unsigned long action,void *data) {mod_timer (&seed_timer, jiffies); +return 0 ; }/*
@@ -556,13 +559,13 @@ static void prandom_timer_start(struct r*/ static int __init prandom_init_late (void ) { -static struct random_ready_callback random_ready = { - .func = prandom_timer_start +static struct notifier_block random_ready = { + .notifier_call = prandom_timer_start }; -int ret =add_random_ready_callback (&random_ready); +int ret =register_random_ready_notifier (&random_ready);if (ret == -EALREADY ) { -prandom_timer_start (&random_ready); +prandom_timer_start (&random_ready,0 ,NULL ); ret =0 ; }return ret;
Greg Kroah-Hartman
maintainerPATCH 162/264 random: use SipHash as interrupt entropy accumulator
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit f5eab0e2db4f881fb2b62b3fdad5b9be673dd7ae upstream.
The current fast_mix() function is a piece of classic mailing list crypto, where it just sort of sprung up by an anonymous author without a lot of real analysis of what precisely it was accomplishing. As an ARX permutation alone, there are some easily searchable differential trails in it, and as a means of preventing malicious interrupts, it completely fails, since it xors new data into the entire state every time. It can't really be analyzed as a random permutation, because it clearly isn't, and it can't be analyzed as an interesting linear algebraic structure either, because it's also not that. There really is very little one can say about it in terms of entropy accumulation. It might diffuse bits, some of the time, maybe, we hope, I guess. But for the most part, it fails to accomplish anything concrete.
As a reminder, the simple goal of add_interrupt_randomness() is to simply accumulate entropy until ~64 interrupts have elapsed, and then dump it into the main input pool, which uses a cryptographic hash.
It would be nice to have something cryptographically strong in the interrupt handler itself, in case a malicious interrupt compromises a per-cpu fast pool within the 64 interrupts / 1 second window, and then inside of that same window somehow can control its return address and cycle counter, even if that's a bit far fetched. However, with a very CPU-limited budget, actually doing that remains an active research project (and perhaps there'll be something useful for Linux to come out of it). And while the abundance of caution would be nice, this isn't *currently* the security model, and we don't yet have a fast enough solution to make it our security model. Plus there's not exactly a pressing need to do that. (And for the avoidance of doubt, the actual cluster of 64 accumulated interrupts still gets dumped into our cryptographically secure input pool.)
So, for now we are going to stick with the existing interrupt security model, which assumes that each cluster of 64 interrupt data samples is mostly non-malicious and not colluding with an infoleaker. With this as our goal, we have a few more choices, simply aiming to accumulate entropy, while discarding the least amount of it.
We know from <https://eprint.iacr.org/2019/198> that random oracles, instantiated as computational hash functions, make good entropy accumulators and extractors, which is the justification for using BLAKE2s in the main input pool. As mentioned, we don't have that luxury here, but we also don't have the same security model requirements, because we're assuming that there aren't malicious inputs. A pseudorandom function instance can approximately behave like a random oracle, provided that the key is uniformly random. But since we're not concerned with malicious inputs, we can pick a fixed key, which is not secret, knowing that "nature" won't interact with a sufficiently chosen fixed key by accident. So we pick a PRF with a fixed initial key, and accumulate into it continuously, dumping the result every 64 interrupts into our cryptographically secure input pool.
For this, we make use of SipHash-1-x on 64-bit and HalfSipHash-1-x on 32-bit, which are already in use in the kernel's hsiphash family of functions and achieve the same performance as the function they replace. It would be nice to do two rounds, but we don't exactly have the CPU budget handy for that, and one round alone is already sufficient.
As mentioned, we start with a fixed initial key (zeros is fine), and allow SipHash's symmetry breaking constants to turn that into a useful starting point. Also, since we're dumping the result (or half of it on 64-bit so as to tax our hash function the same amount on all platforms) into the cryptographically secure input pool, there's no point in finalizing SipHash's output, since it'll wind up being finalized by something much stronger. This means that all we need to do is use the ordinary round function word-by-word, as normal SipHash does. Simplified, the flow is as follows:
Initialize:
siphash_state_t state;
siphash_init(&state, key={0, 0, 0, 0});Update (accumulate) on interrupt:
siphash_update(&state, interrupt_data_and_timing);
Dump into input pool after 64 interrupts:
blake2s_update(&input_pool, &state, sizeof(state) / 2);
The result of all of this is that the security model is unchanged from before -- we assume non-malicious inputs -- yet we now implement that model with a stronger argument. I would like to emphasize, again, that the purpose of this commit is to improve the existing design, by making it analyzable, without changing any fundamental assumptions. There may well be value down the road in changing up the existing design, using something cryptographically strong, or simply using a ring buffer of samples rather than having a fast_mix() at all, or changing which and how much data we collect each interrupt so that we can use something linear, or a variety of other ideas. This commit does not invalidate the potential for those in the future.
For example, in the future, if we're able to characterize the data we're collecting on each interrupt, we may be able to inch toward information theoretic accumulators. <https://eprint.iacr.org/2021/523> shows that s = ror32(s, 7) ^ x and s = ror64(s, 19) ^ x make very good accumulators for 2-monotone distributions, which would apply to timestamp counters, like random_get_entropy() or jiffies, but would not apply to our current combination of the two values, or to the various function addresses and register values we mix in. Alternatively,
<https://eprint.iacr.org/2021/1002> shows that max-period linear functions with no non-trivial invariant subspace make good extractors, used in the form s = f(s) ^ x. However, this only works if the input data is both identical and independent, and obviously a collection of address values and counters fails; so it goes with theoretical papers. Future directions here may involve trying to characterize more precisely what we actually need to collect in the interrupt handler, and building something specific around that.
However, as mentioned, the morass of data we're gathering at the interrupt handler presently defies characterization, and so we use SipHash for now, which works well and performs well.
--- drivers/char/random.c | 94 +++++++++++++++++++++++++++++--------------------- 1 file changed, 55 insertions(+), 39 deletions(-)
drivers/char/random.c +55 -39
@@ -1143,48 +1143,51 @@ void add_bootloader_randomness(const voiEXPORT_SYMBOL_GPL (add_bootloader_randomness);struct fast_pool { -union { -u32 pool32[4 ]; -u64 pool64[2 ]; - };struct work_struct mix; +unsigned long pool[4 ];unsigned long last;unsigned int count;u16 reg_idx; }; +static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = { +#ifdef CONFIG_64BIT +/* SipHash constants */ + .pool = { 0x736f6d6570736575UL, 0x646f72616e646f6dUL, + 0x6c7967656e657261UL, 0x7465646279746573UL } +#else +/* HalfSipHash constants */ + .pool = { 0, 0, 0x6c796765U, 0x74656462U } +#endif +}; +/* -* This is a fast mixing routine used by the interrupt randomness -* collector. It's hardcoded for an 128 bit pool and assumes that any -* locks that might be needed are taken by the caller. +* This is [Half]SipHash-1-x, starting from an empty key. Because +* the key is fixed, it assumes that its inputs are non-malicious, +* and therefore this has no security on its own. s represents the +* 128 or 256-bit SipHash state, while v represents a 128-bit input. */ -static void fast_mix (u32 pool[4 ]) +static void fast_mix (unsigned long s[4 ],const unsigned long *v) { -u32 a = pool[0 ], b = pool[1 ]; -u32 c = pool[2 ], d = pool[3 ]; - - a += b; c += d; - b =rol32 (b,6 ); d =rol32 (d,27 ); - d ^= a; b ^= c; - - a += b; c += d; - b =rol32 (b,16 ); d =rol32 (d,14 ); - d ^= a; b ^= c; - - a += b; c += d; - b =rol32 (b,6 ); d =rol32 (d,27 ); - d ^= a; b ^= c; - - a += b; c += d; - b =rol32 (b,16 ); d =rol32 (d,14 ); - d ^= a; b ^= c; +size_t i; - pool[0 ] = a; pool[1 ] = b; - pool[2 ] = c; pool[3 ] = d; +for (i =0 ; i <16 /sizeof (long ); ++i) { + s[3 ] ^= v[i]; +#ifdef CONFIG_64BIT + s[0 ] += s[1 ]; s[1 ] =rol64 (s[1 ],13 ); s[1 ] ^= s[0 ]; s[0 ] =rol64 (s[0 ],32 ); + s[2 ] += s[3 ]; s[3 ] =rol64 (s[3 ],16 ); s[3 ] ^= s[2 ]; + s[0 ] += s[3 ]; s[3 ] =rol64 (s[3 ],21 ); s[3 ] ^= s[0 ]; + s[2 ] += s[1 ]; s[1 ] =rol64 (s[1 ],17 ); s[1 ] ^= s[2 ]; s[2 ] =rol64 (s[2 ],32 ); +#else + s[0 ] += s[1 ]; s[1 ] =rol32 (s[1 ],5 ); s[1 ] ^= s[0 ]; s[0 ] =rol32 (s[0 ],16 ); + s[2 ] += s[3 ]; s[3 ] =rol32 (s[3 ],8 ); s[3 ] ^= s[2 ]; + s[0 ] += s[3 ]; s[3 ] =rol32 (s[3 ],7 ); s[3 ] ^= s[0 ]; + s[2 ] += s[1 ]; s[1 ] =rol32 (s[1 ],13 ); s[1 ] ^= s[2 ]; s[2 ] =rol32 (s[2 ],16 ); +#endif + s[0 ] ^= v[i]; + } } -static DEFINE_PER_CPU(struct fast_pool, irq_randomness); -#ifdef CONFIG_SMP /* * This function is called when the CPU has just come online, with
@@ -1226,7 +1229,15 @@ static unsigned long get_reg(struct faststatic void mix_interrupt_randomness (struct work_struct *work) { struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix); -u32 pool[4 ]; +/* +* The size of the copied stack pool is explicitly 16 bytes so that we +* tax mix_pool_byte()'s compression function the same amount on all +* platforms. This means on 64-bit we copy half the pool into this, +* while on 32-bit we copy all of it. The entropy is supposed to be +* sufficiently dispersed between bits that in the sponge-like +* half case, on average we don't wind up "losing" some. +*/ +u8 pool[16 ];/* Check to see if we're running on the wrong CPU due to hotplug. */ local_irq_disable ();
@@ -1239,7 +1250,7 @@ static void mix_interrupt_randomness(str* Copy the pool to the stack so that the mixer always has a * consistent view, before we reenable irqs again. */ -memcpy (pool, fast_pool->pool32,sizeof (pool)); +memcpy (pool, fast_pool->pool,sizeof (pool)); fast_pool->count =0 ; fast_pool->last = jiffies;local_irq_enable ();
@@ -1263,25 +1274,30 @@ void add_interrupt_randomness(int irq)struct fast_pool *fast_pool =this_cpu_ptr (&irq_randomness);struct pt_regs *regs =get_irq_regs ();unsigned int new_count; +union { +u32 u32[4 ]; +u64 u64[2 ]; +unsigned long longs[16 /sizeof (long )]; + } irq_data;if (cycles ==0 ) cycles =get_reg (fast_pool, regs);if (sizeof (cycles) ==8 ) - fast_pool->pool64[0 ] ^= cycles ^rol64 (now,32 ) ^ irq; + irq_data.u64[0 ] = cycles ^rol64 (now,32 ) ^ irq;else { - fast_pool->pool32[0 ] ^= cycles ^ irq; - fast_pool->pool32[1 ] ^= now; + irq_data.u32[0 ] = cycles ^ irq; + irq_data.u32[1 ] = now; }if (sizeof (unsigned long ) ==8 ) - fast_pool->pool64[1 ] ^= regs ?instruction_pointer (regs) : _RET_IP_; + irq_data.u64[1 ] = regs ?instruction_pointer (regs) : _RET_IP_;else { - fast_pool->pool32[2 ] ^= regs ?instruction_pointer (regs) : _RET_IP_; - fast_pool->pool32[3 ] ^=get_reg (fast_pool, regs); + irq_data.u32[2 ] = regs ?instruction_pointer (regs) : _RET_IP_; + irq_data.u32[3 ] =get_reg (fast_pool, regs); } -fast_mix (fast_pool->pool32); +fast_mix (fast_pool->pool, irq_data.longs); new_count = ++fast_pool->count;if (new_count &MIX_INFLIGHT )
Greg Kroah-Hartman
maintainerPATCH 163/264 random: make consistent usage of crng_ready()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a96cfe2d427064325ecbf56df8816c6b871ec285 upstream.
Rather than sometimes checking crng_init < 2, we should always use the crng_ready() macro, so that should we change anything later, it's consistent. Additionally, that macro already has a likely() around it, which means we don't need to open code our own likely() and unlikely() annotations.
--- drivers/char/random.c | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-)
drivers/char/random.c +7 -12
@@ -126,18 +126,13 @@ static void try_to_generate_entropy(void*/ int wait_for_random_bytes (void ) { -if (likely (crng_ready ())) -return 0 ; - -do { +while (!crng_ready ()) {int ret; ret =wait_event_interruptible_timeout (crng_init_wait,crng_ready (),HZ );if (ret)return ret >0 ?0 : ret; -try_to_generate_entropy (); - }while (!crng_ready ()); - + }return 0 ; }EXPORT_SYMBOL (wait_for_random_bytes);
@@ -292,7 +287,7 @@ static void crng_reseed(void) ++next_gen;WRITE_ONCE (base_crng.generation, next_gen);WRITE_ONCE (base_crng.birth, jiffies); -if (crng_init <2 ) { +if (!crng_ready ()) { crng_init =2 ; finalize_init = true; }
@@ -360,7 +355,7 @@ static void crng_make_state(u32 chacha_s* ready, we do fast key erasure with the base_crng directly, because * this is what crng_pre_init_inject() mutates during early init. */ -if (unlikely (!crng_ready ())) { +if (!crng_ready ()) {bool ready;spin_lock_irqsave (&base_crng.lock, flags);
@@ -800,7 +795,7 @@ static void credit_entropy_bits(size_t n entropy_count = min_t(unsigned int, POOL_BITS, orig + add); }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); -if (crng_init <2 && entropy_count >=POOL_MIN_BITS ) +if (!crng_ready () && entropy_count >=POOL_MIN_BITS )crng_reseed (); }
@@ -957,7 +952,7 @@ int __init rand_initialize(void)extract_entropy (base_crng.key,sizeof (base_crng.key)); ++base_crng.generation; -if (arch_init && trust_cpu && crng_init <2 ) { +if (arch_init && trust_cpu && !crng_ready ()) { crng_init =2 ;pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); }
@@ -1546,7 +1541,7 @@ static long random_ioctl(struct file *f,case RNDRESEEDCRNG :if (!capable (CAP_SYS_ADMIN ))return -EPERM ; -if (crng_init <2 ) +if (!crng_ready ())return -ENODATA ;crng_reseed ();return 0 ;
Greg Kroah-Hartman
maintainerPATCH 164/264 random: reseed more often immediately after booting
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 7a7ff644aeaf071d433caffb3b8ea57354b55bd3 upstream.
In order to chip away at the "premature first" problem, we augment our existing entropy accounting with more frequent reseedings at boot.
The idea is that at boot, we're getting entropy from various places, and we're not very sure which of early boot entropy is good and which isn't. Even when we're crediting the entropy, we're still not totally certain that it's any good. Since boot is the one time (aside from a compromise) that we have zero entropy, it's important that we shepherd entropy into the crng fairly often.
At the same time, we don't want a "premature next" problem, whereby an attacker can brute force individual bits of added entropy. In lieu of going full-on Fortuna (for now), we can pick a simpler strategy of just reseeding more often during the first 5 minutes after boot. This is still bounded by the 256-bit entropy credit requirement, so we'll skip a reseeding if we haven't reached that, but in case entropy /is/ coming in, this ensures that it makes its way into the crng rather rapidly during these early stages.
Ordinarily we reseed if the previous reseeding is 300 seconds old. This commit changes things so that for the first 600 seconds of boot time, we reseed if the previous reseeding is uptime / 2 seconds old. That means that we'll reseed at the very least double the uptime of the previous reseeding.
--- drivers/char/random.c | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-)
drivers/char/random.c +25 -3
@@ -337,6 +337,28 @@ static void crng_fast_key_erasure(u8 key }/* +* Return whether the crng seed is considered to be sufficiently +* old that a reseeding might be attempted. This happens if the last +* reseeding was CRNG_RESEED_INTERVAL ago, or during early boot, at +* an interval proportional to the uptime. +*/ +static bool crng_has_old_seed (void ) +{ +static bool early_boot = true; +unsigned long interval =CRNG_RESEED_INTERVAL ; + +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 + interval = max_t(unsigned int, 5 * HZ, + (unsigned int )uptime /2 *HZ ); + } +return time_after (jiffies,READ_ONCE (base_crng.birth) + interval); +} + +/* * 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.
@@ -369,10 +391,10 @@ static void crng_make_state(u32 chacha_s }/* -* If the base_crng is more than 5 minutes old, we reseed, which -* in turn bumps the generation counter that we check below. +* If the base_crng is old enough, we try to reseed, which in turn +* bumps the generation counter that we check below. */ -if (unlikely (time_after (jiffies,READ_ONCE (base_crng.birth) +CRNG_RESEED_INTERVAL ))) +if (unlikely (crng_has_old_seed ()))crng_reseed ();local_irq_save (flags);
Greg Kroah-Hartman
maintainerPATCH 165/264 random: check for signal and try earlier when generating entropy
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 3e504d2026eb6c8762cd6040ae57db166516824a upstream.
Rather than waiting a full second in an interruptable waiter before trying to generate entropy, try to generate entropy first and wait second. While waiting one second might give an extra second for getting entropy from elsewhere, we're already pretty late in the init process here, and whatever else is generating entropy will still continue to contribute. This has implications on signal handling: we call try_to_generate_entropy() from wait_for_random_bytes(), and wait_for_random_bytes() always uses wait_event_interruptible_timeout() when waiting, since it's called by userspace code in restartable contexts, where signals can pend. Since try_to_generate_entropy() now runs first, if a signal is pending, it's necessary for try_to_generate_entropy() to check for signals, since it won't hit the wait until after try_to_generate_entropy() has returned. And even before this change, when entering a busy loop in try_to_generate_entropy(), we should have been checking to see if any signals are pending, so that a process doesn't get stuck in that loop longer than expected.
--- drivers/char/random.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/char/random.c +3 -2
@@ -128,10 +128,11 @@ 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; -try_to_generate_entropy (); }return 0 ; }
@@ -1367,7 +1368,7 @@ static void try_to_generate_entropy(voidreturn ;__setup_timer_on_stack (&stack.timer, entropy_timer,0 ,0 ); -while (!crng_ready ()) { +while (!crng_ready () && !signal_pending (current)) {if (!timer_pending (&stack.timer))mod_timer (&stack.timer, jiffies +1 );mix_pool_bytes (&stack.cycles,sizeof (stack.cycles));
Greg Kroah-Hartman
maintainerPATCH 166/264 random: skip fast_init if hwrng provides large chunk of entropy
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit af704c856e888fb044b058d731d61b46eeec499d upstream.
At boot time, EFI calls add_bootloader_randomness(), which in turn calls add_hwgenerator_randomness(). Currently add_hwgenerator_randomness() feeds the first 64 bytes of randomness to the "fast init" non-crypto-grade phase. But if add_hwgenerator_randomness() gets called with more than POOL_MIN_BITS of entropy, there's no point in passing it off to the "fast init" stage, since that's enough entropy to bootstrap the real RNG. The "fast init" stage is just there to provide _something_ in the case where we don't have enough entropy to properly bootstrap the RNG. But if we do have enough entropy to bootstrap the RNG, the current logic doesn't serve a purpose. So, in the case where we're passed greater than or equal to POOL_MIN_BITS of entropy, this commit makes us skip the "fast init" phase.
--- drivers/char/random.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/char/random.c +1 -1
@@ -1121,7 +1121,7 @@ void rand_initialize_disk(struct gendiskvoid add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy) { -if (unlikely (crng_init ==0 )) { +if (unlikely (crng_init ==0 && entropy <POOL_MIN_BITS )) {size_t ret =crng_pre_init_inject (buffer, count, true);mix_pool_bytes (buffer, ret); count -= ret;
Greg Kroah-Hartman
maintainerPATCH 167/264 random: treat bootloader trust toggle the same way as cpu trust toggle
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit d97c68d178fbf8aaaf21b69b446f2dfb13909316 upstream.
If CONFIG_RANDOM_TRUST_CPU is set, the RNG initializes using RDRAND. But, the user can disable (or enable) this behavior by setting random.trust_cpu=0/1 on the kernel command line. This allows system builders to do reasonable things while avoiding howls from tinfoil hatters. (Or vice versa.)
CONFIG_RANDOM_TRUST_BOOTLOADER is basically the same thing, but regards the seed passed via EFI or device tree, which might come from RDRAND or a TPM or somewhere else. In order to allow distros to more easily enable this while avoiding those same howls (or vice versa), this commit adds the corresponding random.trust_bootloader=0/1 toggle.
--- Documentation/kernel-parameters.txt | 6 ++++++ drivers/char/Kconfig | 3 ++- drivers/char/random.c | 8 +++++++- 3 files changed, 15 insertions(+), 2 deletions(-)
Documentation/kernel-parameters.txt +6 -0
@@ -3583,6 +3583,12 @@ bytes respectively. Such letter suffixes fully seed the kernel's CRNG. Default is controlled by CONFIG_RANDOM_TRUST_CPU. + random.trust_bootloader={on,off} + [KNL] Enable or disable trusting the use of a + seed passed by the bootloader (if available) to + fully seed the kernel's CRNG. Default is controlled + by CONFIG_RANDOM_TRUST_BOOTLOADER. + rcu_nocbs= [KNL] The argument is a cpu list, as described above.
drivers/char/Kconfig +2 -1
@@ -617,4 +617,5 @@ config RANDOM_TRUST_BOOTLOADER device randomness. Say Y here to assume the entropy provided by the booloader is trustworthy so it will be added to the kernel's entropy pool. Otherwise, say N here so it will be regarded as device input that - only mixes the entropy pool. + only mixes the entropy pool. This can also be configured at boot with + "random.trust_bootloader=on/off".
drivers/char/random.c +7 -1
@@ -941,11 +941,17 @@ static bool drain_entropy(void *buf, siz**********************************************************************/ static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU ); +static bool trust_bootloader__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_BOOTLOADER );static int __init parse_trust_cpu (char *arg) {return kstrtobool (arg, &trust_cpu); } +static int __init parse_trust_bootloader (char *arg) +{ +return kstrtobool (arg, &trust_bootloader); +}early_param ("random.trust_cpu" , parse_trust_cpu); +early_param ("random.trust_bootloader" , parse_trust_bootloader);/* * The first collection of entropy occurs at system boot while interrupts
@@ -1153,7 +1159,7 @@ EXPORT_SYMBOL_GPL(add_hwgenerator_random*/ void add_bootloader_randomness (const void *buf,size_t size) { -if (IS_ENABLED (CONFIG_RANDOM_TRUST_BOOTLOADER )) +if (trust_bootloader)add_hwgenerator_randomness (buf, size, size *8 );else add_device_randomness (buf, size);
Greg Kroah-Hartman
maintainerPATCH 168/264 random: re-add removed comment about get_random_{u32,u64} reseeding
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit dd7aa36e535797926d8eb311da7151919130139d upstream.
The comment about get_random_{u32,u64}() not invoking reseeding got added in an unrelated commit, that then was recently reverted by 0313bc278dac ("Revert "random: block in /dev/urandom""). So this adds that little comment snippet back, and improves the wording a bit too.
--- drivers/char/random.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/char/random.c +4 -3
@@ -227,9 +227,10 @@ static void _warn_unseeded_randomness(co* * 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 integer family of functions may be -* higher performance for one-off random integers, because they do a -* bit of buffering. +* a read from /dev/urandom. The u32, u64, int, and 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. * *********************************************************************/
Greg Kroah-Hartman
maintainerPATCH 169/264 random: mix build-time latent entropy into pool at init
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 1754abb3e7583c570666fa1e1ee5b317e88c89a0 upstream.
Prior, the "input_pool_data" array needed no real initialization, and so it was easy to mark it with __latent_entropy to populate it during compile-time. In switching to using a hash function, this required us to specifically initialize it to some specific state, which means we dropped the __latent_entropy attribute. An unfortunate side effect was this meant the pool was no longer seeded using compile-time random data. In order to bring this back, we declare an array in rand_initialize() with __latent_entropy and call mix_pool_bytes() on that at init, which accomplishes the same thing as before. We make this __initconst, so that it doesn't take up space at runtime after init.
--- drivers/char/random.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/char/random.c +5 -0
@@ -968,6 +968,11 @@ int __init rand_initialize(void)bool arch_init = true;unsigned long rv; +#if defined(LATENT_ENTROPY_PLUGIN ) + static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy; +_mix_pool_bytes (compiletime_seed,sizeof (compiletime_seed)); +#endif +for (i =0 ; i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) {if (!arch_get_random_seed_long_early (&rv) && !arch_get_random_long_early (&rv)) {
Greg Kroah-Hartman
maintainerPATCH 170/264 random: do not split fast init input in add_hwgenerator_randomness()
In reply to Greg Kroah-HartmanFrom: Jan Varho <[email protected]>
commit 527a9867af29ff89f278d037db704e0ed50fb666 upstream.
add_hwgenerator_randomness() tries to only use the required amount of input for fast init, but credits all the entropy, rather than a fraction of it. Since it's hard to determine how much entropy is left over out of a non-unformly random sample, either give it all to fast init or credit it, but don't attempt to do both. In the process, we can clean up the injection code to no longer need to return a value.
--- drivers/char/random.c | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-)
drivers/char/random.c +6 -17
@@ -438,11 +438,8 @@ static void crng_make_state(u32 chacha_s* This shouldn't be set by functions like add_device_randomness(), * where we can't trust the buffer passed to it is guaranteed to be * unpredictable (so it might not have any entropy at all). -* -* Returns the number of bytes processed from input, which is bounded -* by CRNG_INIT_CNT_THRESH if account is true. */ -static size_t crng_pre_init_inject (const void *input,size_t len,bool account) +static void crng_pre_init_inject (const void *input,size_t len,bool account) {static int crng_init_cnt =0 ;struct blake2s_state hash;
@@ -453,18 +450,15 @@ static size_t crng_pre_init_inject(constspin_lock_irqsave (&base_crng.lock, flags);if (crng_init !=0 ) {spin_unlock_irqrestore (&base_crng.lock, flags); -return 0 ; +return ; } -if (account) - len =min_t (size_t, len,CRNG_INIT_CNT_THRESH - crng_init_cnt); -blake2s_update (&hash, base_crng.key,sizeof (base_crng.key));blake2s_update (&hash, input, len);blake2s_final (&hash, base_crng.key);if (account) { - crng_init_cnt += len; + crng_init_cnt +=min_t (size_t, len,CRNG_INIT_CNT_THRESH - crng_init_cnt);if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { ++base_crng.generation; crng_init =1 ;
@@ -475,8 +469,6 @@ static size_t crng_pre_init_inject(constif (crng_init ==1 )pr_notice ("fast init done\n" ); - -return len; }static void _get_random_bytes (void *buf,size_t nbytes)
@@ -1134,12 +1126,9 @@ void add_hwgenerator_randomness(const vo size_t entropy) {if (unlikely (crng_init ==0 && entropy <POOL_MIN_BITS )) { -size_t ret =crng_pre_init_inject (buffer, count, true); -mix_pool_bytes (buffer, ret); - count -= ret; - buffer += ret; -if (!count || crng_init ==0 ) -return ; +crng_pre_init_inject (buffer, count, true); +mix_pool_bytes (buffer, count); +return ; }/*
Greg Kroah-Hartman
maintainerPATCH 171/264 random: do not allow user to keep crng key around on stack
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit aba120cc101788544aa3e2c30c8da88513892350 upstream.
The fast key erasure RNG design relies on the key that's used to be used and then discarded. We do this, making judicious use of memzero_explicit(). However, reads to /dev/urandom and calls to getrandom() involve a copy_to_user(), and userspace can use FUSE or userfaultfd, or make a massive call, dynamically remap memory addresses as it goes, and set the process priority to idle, in order to keep a kernel stack alive indefinitely. By probing /proc/sys/kernel/random/entropy_avail to learn when the crng key is refreshed, a malicious userspace could mount this attack every 5 minutes thereafter, breaking the crng's forward secrecy.
In order to fix this, we just overwrite the stack's key with the first 32 bytes of the "free" fast key erasure output. If we're returning <= 32 bytes to the user, then we can still return those bytes directly, so that short reads don't become slower. And for long reads, the difference is hopefully lost in the amortization, so it doesn't change much, with that amortization helping variously for medium reads.
We don't need to do this for get_random_bytes() and the various kernel-space callers, and later, if we ever switch to always batching, this won't be necessary either, so there's no need to change the API of these functions.
--- drivers/char/random.c | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-)
drivers/char/random.c +23 -12
@@ -533,19 +533,29 @@ static ssize_t get_random_bytes_user(voiif (!nbytes)return 0 ; - len =min_t (size_t,32 , nbytes); -crng_make_state (chacha_state, output, len); - -if (copy_to_user (buf, output, len)) -return -EFAULT ; - nbytes -= len; - buf += len; - ret += len; +/* +* Immediately overwrite the ChaCha key at index 4 with random +* bytes, in case userspace causes copy_to_user() below to sleep +* forever, so that we still retain forward secrecy in that case. +*/ +crng_make_state (chacha_state, (u8 *)&chacha_state[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 (nbytes <=CHACHA_KEY_SIZE ) { + ret =copy_to_user (buf, &chacha_state[4 ], nbytes) ? -EFAULT : nbytes; + goto out_zero_chacha; + } -while (nbytes) { + do { if (large_request && need_resched()) { -if (signal_pending (current)) + if (signal_pending(current)) { + if (!ret) + ret = -ERESTARTSYS; break; + } schedule(); }
@@ -562,10 +572,11 @@ static ssize_t get_random_bytes_user(voi nbytes -= len; buf += len; ret += len; - } + }while (nbytes); -memzero_explicit (chacha_state,sizeof (chacha_state));memzero_explicit (output,sizeof (output)); +out_zero_chacha: +memzero_explicit (chacha_state,sizeof (chacha_state));return ret; }
Greg Kroah-Hartman
maintainerPATCH 172/264 random: check for signal_pending() outside of need_resched() check
In reply to Greg Kroah-HartmanFrom: Jann Horn <[email protected]>
commit 1448769c9cdb69ad65287f4f7ab58bc5f2f5d7ba upstream.
signal_pending() checks TIF_NOTIFY_SIGNAL and TIF_SIGPENDING, which signal that the task should bail out of the syscall when possible. This is a separate concept from need_resched(), which checks TIF_NEED_RESCHED, signaling that the task should preempt.
In particular, with the current code, the signal_pending() bailout probably won't work reliably.
Change this to look like other functions that read lots of data, such as read_zero().
--- drivers/char/random.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/char/random.c +2 -2
@@ -550,13 +550,13 @@ static ssize_t get_random_bytes_user(voi } do { - if (large_request && need_resched()) { + if (large_request) { if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } - schedule(); + cond_resched(); } chacha20_block(chacha_state, output);
Greg Kroah-Hartman
maintainerPATCH 173/264 random: check for signals every PAGE_SIZE chunk of /dev/[u]random
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit e3c1c4fd9e6d14059ed93ebfe15e1c57793b1a05 upstream.
In 1448769c9cdb ("random: check for signal_pending() outside of need_resched() check"), Jann pointed out that we previously were only checking the TIF_NOTIFY_SIGNAL and TIF_SIGPENDING flags if the process had TIF_NEED_RESCHED set, which meant in practice, super long reads to /dev/[u]random would delay signal handling by a long time. I tried this using the below program, and indeed I wasn't able to interrupt a /dev/urandom read until after several megabytes had been read. The bug he fixed has always been there, and so code that reads from /dev/urandom without checking the return value of read() has mostly worked for a long time, for most sizes, not just for <= 256.
Maybe it makes sense to keep that code working. The reason it was so small prior, ignoring the fact that it didn't work anyway, was likely because /dev/random used to block, and that could happen for pretty large lengths of time while entropy was gathered. But now, it's just a chacha20 call, which is extremely fast and is just operating on pure data, without having to wait for some external event. In that sense, /dev/[u]random is a lot more like /dev/zero.
Taking a page out of /dev/zero's read_zero() function, it always returns at least one chunk, and then checks for signals after each chunk. Chunk sizes there are of length PAGE_SIZE. Let's just copy the same thing for /dev/[u]random, and check for signals and cond_resched() for every PAGE_SIZE amount of data. This makes the behavior more consistent with expectations, and should mitigate the impact of Jann's fix for the age-old signal check bug.
---- test program ----
#include <unistd.h> #include <signal.h> #include <stdio.h> #include <sys/random.h> static unsigned char x[~0U];
static void handle(int) { }
int main(int argc, char *argv[])
{
pid_t pid = getpid(), child;
signal(SIGUSR1, handle);
if (!(child = fork())) {
for (;;)
kill(pid, SIGUSR1);
}
pause();
printf("interrupted after reading %zd bytes\n", getrandom(x, sizeof(x), 0));
kill(child, SIGTERM);
return 0;
}--- drivers/char/random.c | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-)
drivers/char/random.c +20 -21
@@ -524,9 +524,7 @@ EXPORT_SYMBOL(get_random_bytes);static ssize_t get_random_bytes_user (void __user *buf,size_t nbytes) { -bool large_request = nbytes >256 ; -ssize_t ret =0 ; -size_t len; +size_t len, left, ret =0 ;u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)];u8 output[CHACHA20_BLOCK_SIZE ];
@@ -538,46 +536,47 @@ static ssize_t get_random_bytes_user(voi* bytes, in case userspace causes copy_to_user() below to sleep * forever, so that we still retain forward secrecy in that case. */ -crng_make_state (chacha_state, (u8 *)&chacha_state[4 ],CHACHA_KEY_SIZE ); +crng_make_state (chacha_state, (u8 *)&chacha_state[4 ],CHACHA20_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 (nbytes <=CHACHA_KEY_SIZE ) { - ret =copy_to_user (buf, &chacha_state[4 ], nbytes) ? -EFAULT : nbytes; +if (nbytes <=CHACHA20_KEY_SIZE ) { + ret = nbytes -copy_to_user (buf, &chacha_state[4 ], nbytes); goto out_zero_chacha; } -do { -if (large_request) { -if (signal_pending (current)) { -if (!ret) - ret = -ERESTARTSYS ; -break ; - } -cond_resched (); - } - +for (;;) {chacha20_block (chacha_state, output);if (unlikely (chacha_state[12 ] ==0 )) ++chacha_state[13 ]; len =min_t (size_t, nbytes,CHACHA20_BLOCK_SIZE ); -if (copy_to_user (buf, output, len)) { - ret = -EFAULT ; + left =copy_to_user (buf, output, len); +if (left) { + ret += len - left;break ; } - nbytes -= len; buf += len; ret += len; - }while (nbytes); + nbytes -= len; +if (!nbytes) +break ; + +BUILD_BUG_ON (PAGE_SIZE %CHACHA20_BLOCK_SIZE !=0 ); +if (ret %PAGE_SIZE ==0 ) { +if (signal_pending (current)) +break ; +cond_resched (); + } + }memzero_explicit (output,sizeof (output)); out_zero_chacha:memzero_explicit (chacha_state,sizeof (chacha_state)); -return ret; +return ret ? ret : -EFAULT ; }/*
Greg Kroah-Hartman
maintainerPATCH 174/264 random: make random_get_entropy() return an unsigned long
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit b0c3e796f24b588b862b61ce235d3c9417dc8983 upstream.
Some implementations were returning type unsigned long, while others that fell back to get_cycles() were implicitly returning a cycles_t or an untyped constant int literal. That makes for weird and confusing code, and basically all code in the kernel already handled it like it was an unsigned long. I recently tried to handle it as the largest type it could be, a cycles_t, but doing so doesn't really help with much.
Instead let's just make random_get_entropy() return an unsigned long all the time. This also matches the commonly used arch_get_random_long() function, so now RDRAND and RDTSC return the same sized integer, which means one can fallback to the other more gracefully.
--- drivers/char/random.c | 20 +++++++------------- include/linux/timex.h | 2 +- 2 files changed, 8 insertions(+), 14 deletions(-)
drivers/char/random.c +7 -13
@@ -1011,7 +1011,7 @@ int __init rand_initialize(void)*/ void add_device_randomness (const void *buf,size_t size) { -cycles_t cycles =random_get_entropy (); +unsigned long cycles =random_get_entropy ();unsigned long flags, now = jiffies;if (crng_init ==0 && size)
@@ -1042,8 +1042,7 @@ struct timer_rand_state {*/ static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) { -cycles_t cycles =random_get_entropy (); -unsigned long flags, now = jiffies; +unsigned long cycles =random_get_entropy (), now = jiffies, flags;long delta, delta2, delta3;spin_lock_irqsave (&input_pool.lock, flags);
@@ -1298,8 +1297,7 @@ static void mix_interrupt_randomness(strvoid add_interrupt_randomness (int irq) {enum {MIX_INFLIGHT =1U <<31 }; -cycles_t cycles =random_get_entropy (); -unsigned long now = jiffies; +unsigned long cycles =random_get_entropy (), now = jiffies;struct fast_pool *fast_pool =this_cpu_ptr (&irq_randomness);struct pt_regs *regs =get_irq_regs ();unsigned int new_count;
@@ -1312,16 +1310,12 @@ void add_interrupt_randomness(int irq)if (cycles ==0 ) cycles =get_reg (fast_pool, regs); -if (sizeof (cycles) ==8 ) +if (sizeof (unsigned long ) ==8 ) { irq_data.u64[0 ] = cycles ^rol64 (now,32 ) ^ irq; -else { + irq_data.u64[1 ] = regs ?instruction_pointer (regs) : _RET_IP_; + }else { irq_data.u32[0 ] = cycles ^ irq; irq_data.u32[1 ] = now; - } - -if (sizeof (unsigned long ) ==8 ) - irq_data.u64[1 ] = regs ?instruction_pointer (regs) : _RET_IP_; -else { irq_data.u32[2 ] = regs ?instruction_pointer (regs) : _RET_IP_; irq_data.u32[3 ] =get_reg (fast_pool, regs); }
@@ -1368,7 +1362,7 @@ static void entropy_timer(unsigned longstatic void try_to_generate_entropy (void ) {struct { -cycles_t cycles; +unsigned long cycles;struct timer_list timer; } stack;
include/linux/timex.h +1 -1
@@ -75,7 +75,7 @@* By default we use get_cycles() for this purpose, but individual * architectures may override this in their asm/timex.h header file. */ -#define random_get_entropy () get_cycles() +#define random_get_entropy () ((unsigned long)get_cycles())#endif /*
Greg Kroah-Hartman
maintainerPATCH 175/264 random: document crng_fast_key_erasure() destination possibility
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 8717627d6ac53251ee012c3c7aca392f29f38a42 upstream.
This reverts 35a33ff3807d ("random: use memmove instead of memcpy for remaining 32 bytes"), which was made on a totally bogus basis. The thing it was worried about overlapping came from the stack, not from one of its arguments, as Eric pointed out.
But the fact that this confusion even happened draws attention to the fact that it's a bit non-obvious that the random_data parameter can alias chacha_state, and in fact should do so when the caller can't rely on the stack being cleared in a timely manner. So this commit documents that.
--- drivers/char/random.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/char/random.c +7 -0
@@ -319,6 +319,13 @@ static void crng_reseed(void)* 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[4] so +* that this function overwrites it before returning. */ static void crng_fast_key_erasure(u8 key[CHACHA20_KEY_SIZE], u32 chacha_state[CHACHA20_BLOCK_SIZE / sizeof(u32)],
Greg Kroah-Hartman
maintainerPATCH 176/264 random: fix sysctl documentation nits
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 069c4ea6871c18bd368f27756e0f91ffb524a788 upstream.
A semicolon was missing, and the almost-alphabetical-but-not ordering was confusing, so regroup these by category instead.
--- Documentation/sysctl/kernel.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
Documentation/sysctl/kernel.txt +4 -4
@@ -791,6 +791,9 @@ This is a directory, with the following * ``boot_id``: a UUID generated the first time this is retrieved, and unvarying after that; +* ``uuid``: a UUID generated every time this is retrieved (this can + thus be used to generate UUIDs at will); + * ``entropy_avail``: the pool's entropy count, in bits; * ``poolsize``: the entropy pool size, in bits;
@@ -798,10 +801,7 @@ This is a directory, with the following * ``urandom_min_reseed_secs``: obsolete (used to determine the minimum number of seconds between urandom pool reseeding). This file is writable for compatibility purposes, but writing to it has no effect - on any RNG behavior. - -* ``uuid``: a UUID generated every time this is retrieved (this can - thus be used to generate UUIDs at will); + on any RNG behavior; * ``write_wakeup_threshold``: when the entropy count drops below this (as a number of bits), processes waiting to write to ``/dev/random``
Greg Kroah-Hartman
maintainerPATCH 177/264 init: call time_init() before rand_initialize()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit fe222a6ca2d53c38433cba5d3be62a39099e708e upstream.
Currently time_init() is called after rand_initialize(), but rand_initialize() makes use of the timer on various platforms, and sometimes this timer needs to be initialized by time_init() first. In order for random_get_entropy() to not return zero during early boot when it's potentially used as an entropy source, reverse the order of these two calls. The block doing random initialization was right before time_init() before, so changing the order shouldn't have any complicated effects.
--- init/main.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
init/main.c +2 -1
@@ -578,11 +578,13 @@ asmlinkage __visible void __init start_khrtimers_init ();softirq_init ();timekeeping_init (); +time_init ();/* * For best initial stack canary entropy, prepare it after: * - setup_arch() for any UEFI RNG entropy and boot cmdline access * - timekeeping_init() for ktime entropy used in rand_initialize() +* - time_init() for making random_get_entropy() work on some platforms * - rand_initialize() to get any arch-specific entropy like RDRAND * - add_latent_entropy() to get any latent entropy * - adding command line entropy
@@ -592,7 +594,6 @@ asmlinkage __visible void __init start_kadd_device_randomness (command_line,strlen (command_line));boot_init_stack_canary (); -time_init ();sched_clock_postinit ();printk_nmi_init ();perf_event_init ();
Greg Kroah-Hartman
maintainerPATCH 178/264 ia64: define get_cycles macro for arch-override
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 57c0900b91d8891ab43f0e6b464d059fda51d102 upstream.
Itanium defines a get_cycles() function, but it does not do the usual #define get_cycles get_cycles dance, making it impossible for generic code to see if an arch-specific function was defined. While the get_cycles() ifdef is not currently used, the following timekeeping patch in this series will depend on the macro existing (or not existing) when defining random_get_entropy().
--- arch/ia64/include/asm/timex.h | 1 + 1 file changed, 1 insertion(+)
arch/ia64/include/asm/timex.h +1 -0
@@ -38,6 +38,7 @@ get_cycles (void) ret =ia64_getreg (_IA64_REG_AR_ITC);return ret; } +#define get_cycles get_cyclesextern void ia64_cpu_local_tick (void );extern unsigned long long ia64_native_sched_clock (void );
Greg Kroah-Hartman
maintainerPATCH 179/264 s390: define get_cycles macro for arch-override
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 2e3df523256cb9836de8441e9c791a796759bb3c upstream.
S390x defines a get_cycles() function, but it does not do the usual #define get_cycles get_cycles dance, making it impossible for generic code to see if an arch-specific function was defined. While the get_cycles() ifdef is not currently used, the following timekeeping patch in this series will depend on the macro existing (or not existing) when defining random_get_entropy().
--- arch/s390/include/asm/timex.h | 1 + 1 file changed, 1 insertion(+)
arch/s390/include/asm/timex.h +1 -0
@@ -168,6 +168,7 @@ static inline cycles_t get_cycles(void) {return (cycles_t )get_tod_clock () >>2 ; } +#define get_cycles get_cyclesint get_phys_clock (unsigned long long *clock);void init_cpu_timer (void );
Greg Kroah-Hartman
maintainerPATCH 180/264 parisc: define get_cycles macro for arch-override
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 8865bbe6ba1120e67f72201b7003a16202cd42be upstream.
PA-RISC defines a get_cycles() function, but it does not do the usual #define get_cycles get_cycles dance, making it impossible for generic code to see if an arch-specific function was defined. While the get_cycles() ifdef is not currently used, the following timekeeping patch in this series will depend on the macro existing (or not existing) when defining random_get_entropy().
--- arch/parisc/include/asm/timex.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/parisc/include/asm/timex.h +2 -1
@@ -11,9 +11,10 @@typedef unsigned long cycles_t ; -static inline cycles_t get_cycles (void ) +static inline cycles_t get_cycles (void ) {return mfctl (16 ); } +#define get_cycles get_cycles#endif
Greg Kroah-Hartman
maintainerPATCH 181/264 alpha: define get_cycles macro for arch-override
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 1097710bc9660e1e588cf2186a35db3d95c4d258 upstream.
Alpha defines a get_cycles() function, but it does not do the usual #define get_cycles get_cycles dance, making it impossible for generic code to see if an arch-specific function was defined. While the get_cycles() ifdef is not currently used, the following timekeeping patch in this series will depend on the macro existing (or not existing) when defining random_get_entropy().
--- arch/alpha/include/asm/timex.h | 1 + 1 file changed, 1 insertion(+)
arch/alpha/include/asm/timex.h +1 -0
@@ -27,5 +27,6 @@ static inline cycles_t get_cycles (void) __asm__ __volatile__ ("rpcc %0" :"=r" (ret)); return ret; } +#define get_cycles get_cycles#endif
Greg Kroah-Hartman
maintainerPATCH 182/264 powerpc: define get_cycles macro for arch-override
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 408835832158df0357e18e96da7f2d1ed6b80e7f upstream.
PowerPC defines a get_cycles() function, but it does not do the usual #define get_cycles get_cycles dance, making it impossible for generic code to see if an arch-specific function was defined. While the get_cycles() ifdef is not currently used, the following timekeeping patch in this series will depend on the macro existing (or not existing) when defining random_get_entropy().
--- arch/powerpc/include/asm/timex.h | 1 + 1 file changed, 1 insertion(+)
arch/powerpc/include/asm/timex.h +1 -0
@@ -53,6 +53,7 @@ static inline cycles_t get_cycles(void)return ret;#endif } +#define get_cycles get_cycles#endif /* __KERNEL__ */ #endif /* _ASM_POWERPC_TIMEX_H */
Greg Kroah-Hartman
maintainerPATCH 183/264 timekeeping: Add raw clock fallback for random_get_entropy()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 1366992e16bddd5e2d9a561687f367f9f802e2e4 upstream.
The addition of random_get_entropy_fallback() provides access to whichever time source has the highest frequency, which is useful for gathering entropy on platforms without available cycle counters. It's not necessarily as good as being able to quickly access a cycle counter that the CPU has, but it's still something, even when it falls back to being jiffies-based.
In the event that a given arch does not define get_cycles(), falling back to the get_cycles() default implementation that returns 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
Finally, since random_get_entropy_fallback() is used during extremely early boot when randomizing freelists in mm_init(), it can be called before timekeeping has been initialized. In that case there really is nothing we can do; jiffies hasn't even started ticking yet. So just give up and return 0.
--- include/linux/timex.h | 8 ++++++++ kernel/time/timekeeping.c | 16 ++++++++++++++++ 2 files changed, 24 insertions(+)
include/linux/timex.h +8 -0
@@ -62,6 +62,8 @@#include <linux/types.h> #include <linux/param.h> +unsigned long random_get_entropy_fallback (void ); +#include <asm/timex.h> #ifndef random_get_entropy
@@ -74,8 +76,14 @@* * By default we use get_cycles() for this purpose, but individual * architectures may override this in their asm/timex.h header file. +* If a given arch does not have get_cycles(), then we fallback to +* using random_get_entropy_fallback(). */ +#ifdef get_cycles#define random_get_entropy () ((unsigned long)get_cycles()) +#else +#define random_get_entropy () random_get_entropy_fallback() +#endif #endif /*
kernel/time/timekeeping.c +16 -0
@@ -19,6 +19,7 @@#include <linux/clocksource.h> #include <linux/jiffies.h> #include <linux/time.h> +#include <linux/timex.h> #include <linux/tick.h> #include <linux/stop_machine.h> #include <linux/pvclock_gtod.h>
@@ -2270,6 +2271,21 @@ ktime_t ktime_get_update_offsets_now(uns }/** +* random_get_entropy_fallback - Returns the raw clock source value, +* used by random.c for platforms with no valid random_get_entropy(). +*/ +unsigned long random_get_entropy_fallback (void ) +{ +struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono; +struct clocksource *clock =READ_ONCE (tkr->clock); + +if (unlikely (timekeeping_suspended || !clock)) +return 0 ; +return clock->read (clock); +} +EXPORT_SYMBOL_GPL (random_get_entropy_fallback); + +/** * do_adjtimex() - Accessor function to NTP __do_adjtimex function */ int do_adjtimex (struct timex *txc)
Greg Kroah-Hartman
maintainerPATCH 184/264 m68k: use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 0f392c95391f2d708b12971a07edaa7973f9eece upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
--- arch/m68k/include/asm/timex.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/m68k/include/asm/timex.h +1 -1
@@ -34,7 +34,7 @@ static inline unsigned long random_get_e {if (mach_random_get_entropy)return mach_random_get_entropy (); -return 0 ; +return random_get_entropy_fallback (); }#define random_get_entropy random_get_entropy
Greg Kroah-Hartman
maintainerPATCH 185/264 mips: use fallback for random_get_entropy() instead of just c0 random
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 1c99c6a7c3c599a68321b01b9ec243215ede5a68 upstream.
For situations in which we don't have a c0 counter register available, we've been falling back to reading the c0 "random" register, which is usually bounded by the amount of TLB entries and changes every other cycle or so. This means it wraps extremely often. We can do better by combining this fast-changing counter with a potentially slower-changing counter from random_get_entropy_fallback() in the more significant bits. This commit combines the two, taking into account that the changing bits are in a different bit position depending on the CPU model. In addition, we previously were falling back to 0 for ancient CPUs that Linux does not support anyway; remove that dead path entirely.
--- arch/mips/include/asm/timex.h | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
arch/mips/include/asm/timex.h +8 -9
@@ -76,25 +76,24 @@ static inline cycles_t get_cycles(void)else return 0 ;/* no usable counter */ } +#define get_cycles get_cycles/* * Like get_cycles - but where c0_count is not available we desperately * use c0_random in an attempt to get at least a little bit of entropy. -* -* R6000 and R6000A neither have a count register nor a random register. -* That leaves no entropy source in the CPU itself. */ static inline unsigned long random_get_entropy (void ) { -unsigned int prid =read_c0_prid (); -unsigned int imp = prid &PRID_IMP_MASK ; +unsigned int c0_random; -if (can_use_mips_counter (prid)) +if (can_use_mips_counter (read_c0_prid ()))return read_c0_count (); -else if (likely (imp !=PRID_IMP_R6000 && imp !=PRID_IMP_R6000A )) -return read_c0_random (); + +if (cpu_has_3kex) + c0_random = (read_c0_random () >>8 ) &0x3f ;else -return 0 ;/* no usable register */ + c0_random =read_c0_random () &0x3f ; +return (random_get_entropy_fallback () <<6 ) | (0x3f - c0_random); }#define random_get_entropy random_get_entropy
Greg Kroah-Hartman
maintainerPATCH 186/264 arm: use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit ff8a8f59c99f6a7c656387addc4d9f2247d75077 upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
--- arch/arm/include/asm/timex.h | 1 + 1 file changed, 1 insertion(+)
arch/arm/include/asm/timex.h +1 -0
@@ -14,5 +14,6 @@typedef unsigned long cycles_t ;#define get_cycles () ({ cycles_t c; read_current_timer(&c) ? 0 : c; }) +#define random_get_entropy () (((unsigned long)get_cycles()) ?: random_get_entropy_fallback())#endif
Greg Kroah-Hartman
maintainerPATCH 187/264 nios2: use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit c04e72700f2293013dab40208e809369378f224c upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
--- arch/nios2/include/asm/timex.h | 3 +++ 1 file changed, 3 insertions(+)
arch/nios2/include/asm/timex.h +3 -0
@@ -20,5 +20,8 @@typedef unsigned long cycles_t ;extern cycles_t get_cycles (void ); +#define get_cycles get_cycles + +#define random_get_entropy () (((unsigned long)get_cycles()) ?: random_get_entropy_fallback())#endif
Greg Kroah-Hartman
maintainerPATCH 188/264 x86/tsc: Use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 3bd4abc07a267e6a8b33d7f8717136e18f921c53 upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is suboptimal. Instead, fallback to calling random_get_entropy_fallback(), which isn't extremely high precision or guaranteed to be entropic, but is certainly better than returning zero all the time.
If CONFIG_X86_TSC=n, then it's possible for the kernel to run on systems without RDTSC, such as 486 and certain 586, so the fallback code is only required for that case.
As well, fix up both the new function and the get_cycles() function from which it was derived to use cpu_feature_enabled() rather than boot_cpu_has(), and use !IS_ENABLED() instead of #ifndef.
--- arch/x86/include/asm/timex.h | 9 +++++++++ arch/x86/include/asm/tsc.h | 7 +++---- 2 files changed, 12 insertions(+), 4 deletions(-)
arch/x86/include/asm/timex.h +9 -0
@@ -4,6 +4,15 @@#include <asm/processor.h> #include <asm/tsc.h> +static inline unsigned long random_get_entropy (void ) +{ +if (!IS_ENABLED (CONFIG_X86_TSC ) && + !cpu_feature_enabled (X86_FEATURE_TSC )) +return random_get_entropy_fallback (); +return rdtsc (); +} +#define random_get_entropy random_get_entropy +/* Assume we use the PIT time source for the clock tick */ #define CLOCK_TICK_RATE PIT_TICK_RATE
arch/x86/include/asm/tsc.h +3 -4
@@ -21,13 +21,12 @@ extern void disable_TSC(void);static inline cycles_t get_cycles (void ) { -#ifndef CONFIG_X86_TSC -if (!boot_cpu_has (X86_FEATURE_TSC )) +if (!IS_ENABLED (CONFIG_X86_TSC ) && + !cpu_feature_enabled (X86_FEATURE_TSC ))return 0 ; -#endif -return rdtsc (); } +#define get_cycles get_cyclesextern struct system_counterval_t convert_art_to_tsc (cycle_t art);
Greg Kroah-Hartman
maintainerPATCH 189/264 um: use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 9f13fb0cd11ed2327abff69f6501a2c124c88b5a upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
This is accomplished by just including the asm-generic code like on other architectures, which means we can get rid of the empty stub function here.
--- arch/um/include/asm/timex.h | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-)
arch/um/include/asm/timex.h +2 -7
@@ -1,13 +1,8 @@#ifndef __UM_TIMEX_H#define __UM_TIMEX_H -typedef unsigned long cycles_t ; - -static inline cycles_t get_cycles (void ) -{ -return 0 ; -} -#define CLOCK_TICK_RATE (HZ) +#include <asm-generic/timex.h> +#endif
Greg Kroah-Hartman
maintainerPATCH 190/264 sparc: use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit ac9756c79797bb98972736b13cfb239fd2cffb79 upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
This is accomplished by just including the asm-generic code like on other architectures, which means we can get rid of the empty stub function here.
--- arch/sparc/include/asm/timex_32.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
arch/sparc/include/asm/timex_32.h +1 -3
@@ -8,8 +8,6 @@#define CLOCK_TICK_RATE 1193180/* Underlying HZ */ -/* XXX Maybe do something better at some point... -DaveM */ -typedef unsigned long cycles_t ; -#define get_cycles () (0) +#include <asm-generic/timex.h> #endif
Greg Kroah-Hartman
maintainerPATCH 191/264 xtensa: use fallback for random_get_entropy() instead of zero
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit e10e2f58030c5c211d49042a8c2a1b93d40b2ffb upstream.
In the event that random_get_entropy() can't access a cycle counter or similar, falling back to returning 0 is really not the best we can do. Instead, at least calling random_get_entropy_fallback() would be preferable, because that always needs to return _something_, even falling back to jiffies eventually. It's not as though random_get_entropy_fallback() is super high precision or guaranteed to be entropic, but basically anything that's not zero all the time is better than returning zero all the time.
This is accomplished by just including the asm-generic code like on other architectures, which means we can get rid of the empty stub function here.
--- arch/xtensa/include/asm/timex.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
arch/xtensa/include/asm/timex.h +2 -4
@@ -30,10 +30,6 @@extern unsigned long ccount_freq; -typedef unsigned long long cycles_t ; - -#define get_cycles () (0) -void local_timer_setup (unsigned cpu);/*
@@ -69,4 +65,6 @@ static inline void set_linux_timer (unsi WSR_CCOMPARE(LINUX_TIMER, ccompare); } +#include <asm-generic/timex.h> +#endif /* _XTENSA_TIMEX_H */
Greg Kroah-Hartman
maintainerPATCH 192/264 uapi: rename ext2_swab() to swab() and share globally in swab.h
In reply to Greg Kroah-HartmanFrom: Yury Norov <[email protected]>
[ Upstream commit d5767057c9a76a29f073dad66b7fa12a90e8c748 ]
ext2_swab() is defined locally in lib/find_bit.c However it is not specific to ext2, neither to bitmaps.
There are many potential users of it, so rename it to just swab() and move to include/uapi/linux/swab.h
ABI guarantees that size of unsigned long corresponds to BITS_PER_LONG, therefore drop unneeded cast.
--- include/linux/swab.h | 1 + include/uapi/linux/swab.h | 10 ++++++++++ lib/find_bit.c | 16 ++-------------- 3 files changed, 13 insertions(+), 14 deletions(-)
include/linux/swab.h +1 -0
@@ -6,6 +6,7 @@# define swab16 __swab16# define swab32 __swab32# define swab64 __swab64 +# define swab __swab# define swahw32 __swahw32# define swahb32 __swahb32# define swab16p __swab16p
include/uapi/linux/swab.h +10 -0
@@ -3,6 +3,7 @@#include <linux/types.h> #include <linux/compiler.h> +#include <asm/bitsperlong.h> #include <asm/swab.h> /*
@@ -131,6 +132,15 @@ static inline __attribute_const__ __u32 __fswab64(x))#endif +static __always_inline unsigned long __swab (const unsigned long y) +{ +#if BITS_PER_LONG ==64 +return __swab64 (y); +#else /* BITS_PER_LONG == 32 */ +return __swab32 (y); +#endif +} +/** * __swahw32 - return a word-swapped 32-bit value * @x: value to wordswap
lib/find_bit.c +2 -14
@@ -133,18 +133,6 @@ EXPORT_SYMBOL(find_last_bit);#ifdef __BIG_ENDIAN -/* include/linux/byteorder does not support "unsigned long" type */ -static inline unsigned long ext2_swab (const unsigned long y) -{ -#if BITS_PER_LONG ==64 -return (unsigned long )__swab64 ((u64 ) y); -#elif BITS_PER_LONG ==32 -return (unsigned long )__swab32 ((u32 ) y); -#else -#error BITS_PER_LONG not defined -#endif -} -#if !defined(find_next_bit_le) || !defined(find_next_zero_bit_le)static unsigned long _find_next_bit_le (const unsigned long *addr,unsigned long nbits,unsigned long start,unsigned long invert)
@@ -157,7 +145,7 @@ static unsigned long _find_next_bit_le(c tmp = addr[start /BITS_PER_LONG ] ^ invert;/* Handle 1st word. */ - tmp &=ext2_swab (BITMAP_FIRST_WORD_MASK (start)); + tmp &=swab (BITMAP_FIRST_WORD_MASK (start)); start =round_down (start,BITS_PER_LONG );while (!tmp) {
@@ -168,7 +156,7 @@ static unsigned long _find_next_bit_le(c tmp = addr[start / BITS_PER_LONG] ^ invert; } -return min (start +__ffs (ext2_swab (tmp)), nbits); +return min (start +__ffs (swab (tmp)), nbits); }#endif
Greg Kroah-Hartman
maintainerPATCH 193/264 random: insist on random_get_entropy() existing in order to simplify
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 4b758eda851eb9336ca86a0041a4d3da55f66511 upstream.
All platforms are now guaranteed to provide some value for random_get_entropy(). In case some bug leads to this not being so, we print a warning, because that indicates that something is really very wrong (and likely other things are impacted too). This should never be hit, but it's a good and cheap way of finding out if something ever is problematic.
Since we now have viable fallback code for random_get_entropy() on all platforms, which is, in the worst case, not worse than jiffies, we can count on getting the best possible value out of it. That means there's no longer a use for using jiffies as entropy input. It also means we no longer have a reason for doing the round-robin register flow in the IRQ handler, which was always of fairly dubious value.
Instead we can greatly simplify the IRQ handler inputs and also unify the construction between 64-bits and 32-bits. We now collect the cycle counter and the return address, since those are the two things that matter. Because the return address and the irq number are likely related, to the extent we mix in the irq number, we can just xor it into the top unchanging bytes of the return address, rather than the bottom changing bytes of the cycle counter as before. Then, we can do a fixed 2 rounds of SipHash/HSipHash. Finally, we use the same construction of hashing only half of the [H]SipHash state on 32-bit and 64-bit. We're not actually discarding any entropy, since that entropy is carried through until the next time. And more importantly, it lets us do the same sponge-like construction everywhere.
--- drivers/char/random.c | 86 +++++++++++++++----------------------------------- 1 file changed, 26 insertions(+), 60 deletions(-)
drivers/char/random.c +26 -60
@@ -1018,15 +1018,14 @@ int __init rand_initialize(void)*/ void add_device_randomness (const void *buf,size_t size) { -unsigned long cycles =random_get_entropy (); -unsigned long flags, now = jiffies; +unsigned long entropy =random_get_entropy (); +unsigned long flags;if (crng_init ==0 && size)crng_pre_init_inject (buf, size, false);spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (&cycles,sizeof (cycles)); -_mix_pool_bytes (&now,sizeof (now)); +_mix_pool_bytes (&entropy,sizeof (entropy));_mix_pool_bytes (buf, size);spin_unlock_irqrestore (&input_pool.lock, flags); }
@@ -1049,12 +1048,11 @@ struct timer_rand_state {*/ static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) { -unsigned long cycles =random_get_entropy (), now = jiffies, flags; +unsigned long entropy =random_get_entropy (), now = jiffies, flags;long delta, delta2, delta3;spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (&cycles,sizeof (cycles)); -_mix_pool_bytes (&now,sizeof (now)); +_mix_pool_bytes (&entropy,sizeof (entropy));_mix_pool_bytes (&num,sizeof (num));spin_unlock_irqrestore (&input_pool.lock, flags);
@@ -1182,7 +1180,6 @@ struct fast_pool {unsigned long pool[4 ];unsigned long last;unsigned int count; -u16 reg_idx; }; static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
@@ -1200,13 +1197,13 @@ static DEFINE_PER_CPU(struct fast_pool,* This is [Half]SipHash-1-x, starting from an empty key. Because * the key is fixed, it assumes that its inputs are non-malicious, * and therefore this has no security on its own. s represents the -* 128 or 256-bit SipHash state, while v represents a 128-bit input. +* four-word SipHash state, while v represents a two-word input. */ -static void fast_mix (unsigned long s[4 ],const unsigned long *v) +static void fast_mix (unsigned long s[4 ],const unsigned long v[2 ]) {size_t i; -for (i =0 ; i <16 /sizeof (long ); ++i) { +for (i =0 ; i <2 ; ++i) { s[3 ] ^= v[i];#ifdef CONFIG_64BIT s[0 ] += s[1 ]; s[1 ] =rol64 (s[1 ],13 ); s[1 ] ^= s[0 ]; s[0 ] =rol64 (s[0 ],32 );
@@ -1246,33 +1243,17 @@ int random_online_cpu(unsigned int cpu) }#endif -static unsigned long get_reg (struct fast_pool *f,struct pt_regs *regs) -{ -unsigned long *ptr = (unsigned long *)regs; -unsigned int idx; - -if (regs ==NULL ) -return 0 ; - idx =READ_ONCE (f->reg_idx); -if (idx >=sizeof (struct pt_regs ) /sizeof (unsigned long )) - idx =0 ; - ptr += idx++; -WRITE_ONCE (f->reg_idx, idx); -return *ptr; -} -static void mix_interrupt_randomness (struct work_struct *work) { struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);/* -* The size of the copied stack pool is explicitly 16 bytes so that we -* tax mix_pool_byte()'s compression function the same amount on all -* platforms. This means on 64-bit we copy half the pool into this, -* while on 32-bit we copy all of it. The entropy is supposed to be -* sufficiently dispersed between bits that in the sponge-like -* half case, on average we don't wind up "losing" some. +* The size of the copied stack pool is explicitly 2 longs so that we +* only ever ingest half of the siphash output each time, retaining +* the other half as the next "key" that carries over. The entropy is +* supposed to be sufficiently dispersed between bits so on average +* we don't wind up "losing" some. */ -u8 pool[16 ]; +unsigned long pool[2 ];/* Check to see if we're running on the wrong CPU due to hotplug. */ local_irq_disable ();
@@ -1304,36 +1285,21 @@ static void mix_interrupt_randomness(strvoid add_interrupt_randomness (int irq) {enum {MIX_INFLIGHT =1U <<31 }; -unsigned long cycles =random_get_entropy (), now = jiffies; +unsigned long entropy =random_get_entropy ();struct fast_pool *fast_pool =this_cpu_ptr (&irq_randomness);struct pt_regs *regs =get_irq_regs ();unsigned int new_count; -union { -u32 u32[4 ]; -u64 u64[2 ]; -unsigned long longs[16 /sizeof (long )]; - } irq_data; - -if (cycles ==0 ) - cycles =get_reg (fast_pool, regs); - -if (sizeof (unsigned long ) ==8 ) { - irq_data.u64[0 ] = cycles ^rol64 (now,32 ) ^ irq; - irq_data.u64[1 ] = regs ?instruction_pointer (regs) : _RET_IP_; - }else { - irq_data.u32[0 ] = cycles ^ irq; - irq_data.u32[1 ] = now; - irq_data.u32[2 ] = regs ?instruction_pointer (regs) : _RET_IP_; - irq_data.u32[3 ] =get_reg (fast_pool, regs); - } -fast_mix (fast_pool->pool, irq_data.longs); +fast_mix (fast_pool->pool, (unsigned long [2 ]){ + entropy, + (regs ?instruction_pointer (regs) : _RET_IP_) ^swab (irq) + }); new_count = ++fast_pool->count;if (new_count &MIX_INFLIGHT )return ; -if (new_count <64 && (!time_after (now, fast_pool->last +HZ ) || +if (new_count <64 && (!time_is_before_jiffies (fast_pool->last +HZ ) ||unlikely (crng_init ==0 )))return ;
@@ -1369,28 +1335,28 @@ static void entropy_timer(unsigned longstatic void try_to_generate_entropy (void ) {struct { -unsigned long cycles; +unsigned long entropy;struct timer_list timer; } stack; - stack.cycles =random_get_entropy (); + stack.entropy =random_get_entropy ();/* Slow counter - or none. Don't even bother */ -if (stack.cycles ==random_get_entropy ()) +if (stack.entropy ==random_get_entropy ())return ;__setup_timer_on_stack (&stack.timer, entropy_timer,0 ,0 );while (!crng_ready () && !signal_pending (current)) {if (!timer_pending (&stack.timer))mod_timer (&stack.timer, jiffies +1 ); -mix_pool_bytes (&stack.cycles,sizeof (stack.cycles)); +mix_pool_bytes (&stack.entropy,sizeof (stack.entropy));schedule (); - stack.cycles =random_get_entropy (); + stack.entropy =random_get_entropy (); }del_timer_sync (&stack.timer);destroy_timer_on_stack (&stack.timer); -mix_pool_bytes (&stack.cycles,sizeof (stack.cycles)); +mix_pool_bytes (&stack.entropy,sizeof (stack.entropy)); }
Greg Kroah-Hartman
maintainerPATCH 194/264 random: do not use batches when !crng_ready()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit cbe89e5a375a51bbb952929b93fa973416fea74e upstream.
It's too hard to keep the batches synchronized, and pointless anyway, since in !crng_ready(), we're updating the base_crng key really often, where batching only hurts. So instead, if the crng isn't ready, just call into get_random_bytes(). At this stage nothing is performance critical anyhow.
--- drivers/char/random.c | 158 ++++++++++++++++++-------------------------------- 1 file changed, 59 insertions(+), 99 deletions(-)
drivers/char/random.c +59 -99
@@ -234,10 +234,7 @@ static void _warn_unseeded_randomness(co* *********************************************************************/ -enum { -CRNG_RESEED_INTERVAL =300 *HZ , -CRNG_INIT_CNT_THRESH =2 *CHACHA20_KEY_SIZE -}; +enum {CRNG_RESEED_INTERVAL =300 *HZ }; static struct { u8 key[CHACHA20_KEY_SIZE] __aligned(__alignof__(long));
@@ -259,6 +256,8 @@ static DEFINE_PER_CPU(struct crng, crngs/* Used by crng_reseed() to extract a new seed from the input pool. */ static bool drain_entropy (void *buf,size_t nbytes); +/* Used by crng_make_state() to extract a new seed when crng_init==0. */ +static void extract_entropy (void *buf,size_t nbytes);/* * This extracts a new crng key from the input pool, but only if there is a
@@ -383,17 +382,20 @@ static void crng_make_state(u32 chacha_s/* * 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, because -* this is what crng_pre_init_inject() mutates during early init. +* ready, we do fast key erasure with the base_crng directly, extracting +* when crng_init==0. */ if (!crng_ready ()) {bool ready;spin_lock_irqsave (&base_crng.lock, flags); ready =crng_ready (); -if (!ready) +if (!ready) { +if (crng_init ==0 ) +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 ;
@@ -434,50 +436,6 @@ static void crng_make_state(u32 chacha_slocal_irq_restore (flags); } -/* -* This function is for crng_init == 0 only. It loads entropy directly -* into the crng's key, without going through the input pool. It is, -* generally speaking, not very safe, but we use this only at early -* boot time when it's better to have something there rather than -* nothing. -* -* If account is set, then the crng_init_cnt counter is incremented. -* This shouldn't be set by functions like add_device_randomness(), -* where we can't trust the buffer passed to it is guaranteed to be -* unpredictable (so it might not have any entropy at all). -*/ -static void crng_pre_init_inject (const void *input,size_t len,bool account) -{ -static int crng_init_cnt =0 ; -struct blake2s_state hash; -unsigned long flags; - -blake2s_init (&hash,sizeof (base_crng.key)); - -spin_lock_irqsave (&base_crng.lock, flags); -if (crng_init !=0 ) { -spin_unlock_irqrestore (&base_crng.lock, flags); -return ; - } - -blake2s_update (&hash, base_crng.key,sizeof (base_crng.key)); -blake2s_update (&hash, input, len); -blake2s_final (&hash, base_crng.key); - -if (account) { - crng_init_cnt +=min_t (size_t, len,CRNG_INIT_CNT_THRESH - crng_init_cnt); -if (crng_init_cnt >=CRNG_INIT_CNT_THRESH ) { - ++base_crng.generation; - crng_init =1 ; - } - } - -spin_unlock_irqrestore (&base_crng.lock, flags); - -if (crng_init ==1 ) -pr_notice ("fast init done\n" ); -} -static void _get_random_bytes (void *buf,size_t nbytes) {u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)];
@@ -623,6 +581,11 @@ u64 get_random_u64(void)warn_unseeded_randomness (&previous); +if (!crng_ready ()) { +_get_random_bytes (&ret,sizeof (ret)); +return ret; + } +local_irq_save (flags); batch =raw_cpu_ptr (&batched_entropy_u64);
@@ -656,6 +619,11 @@ u32 get_random_u32(void)warn_unseeded_randomness (&previous); +if (!crng_ready ()) { +_get_random_bytes (&ret,sizeof (ret)); +return ret; + } +local_irq_save (flags); batch =raw_cpu_ptr (&batched_entropy_u32);
@@ -777,7 +745,8 @@ EXPORT_SYMBOL(get_random_bytes_arch);enum {POOL_BITS =BLAKE2S_HASH_SIZE *8 , -POOL_MIN_BITS =POOL_BITS /* No point in settling for less. */ +POOL_MIN_BITS =POOL_BITS ,/* No point in settling for less. */ +POOL_FAST_INIT_BITS =POOL_MIN_BITS /2 };/* For notifying userspace should write into /dev/random. */
@@ -814,24 +783,6 @@ static void mix_pool_bytes(const void *ispin_unlock_irqrestore (&input_pool.lock, flags); } -static void credit_entropy_bits (size_t nbits) -{ -unsigned int entropy_count, orig, add; - -if (!nbits) -return ; - - add =min_t (size_t, nbits,POOL_BITS ); - -do { - orig =READ_ONCE (input_pool.entropy_count); - entropy_count = min_t(unsigned int, POOL_BITS, orig + add); - }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); - -if (!crng_ready () && entropy_count >=POOL_MIN_BITS ) -crng_reseed (); -} -/* * This is an HKDF-like construction for using the hashed collected entropy * as a PRF key, that's then expanded block-by-block.
@@ -897,6 +848,33 @@ static bool drain_entropy(void *buf, sizreturn true; } +static void credit_entropy_bits (size_t nbits) +{ +unsigned int entropy_count, orig, add; +unsigned long flags; + +if (!nbits) +return ; + + add =min_t (size_t, nbits,POOL_BITS ); + +do { + orig =READ_ONCE (input_pool.entropy_count); + entropy_count = min_t(unsigned int, POOL_BITS, orig + add); + }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); + +if (!crng_ready () && entropy_count >=POOL_MIN_BITS ) +crng_reseed (); +else if (unlikely (crng_init ==0 && entropy_count >=POOL_FAST_INIT_BITS )) { +spin_lock_irqsave (&base_crng.lock, flags); +if (crng_init ==0 ) { +extract_entropy (base_crng.key,sizeof (base_crng.key)); + crng_init =1 ; + } +spin_unlock_irqrestore (&base_crng.lock, flags); + } +} +/********************************************************************** *
@@ -939,9 +917,9 @@ static bool drain_entropy(void *buf, siz* entropy as specified by the caller. If the entropy pool is full it will * block until more entropy is needed. * -* add_bootloader_randomness() is the same as add_hwgenerator_randomness() or -* add_device_randomness(), depending on whether or not the configuration -* option CONFIG_RANDOM_TRUST_BOOTLOADER is set. +* add_bootloader_randomness() is called by bootloader drivers, such as EFI +* and device tree, and credits its input depending on whether or not the +* configuration option CONFIG_RANDOM_TRUST_BOOTLOADER is set. * * add_interrupt_randomness() uses the interrupt timing as random * inputs to the entropy pool. Using the cycle counters and the irq source
@@ -1021,9 +999,6 @@ void add_device_randomness(const void *bunsigned long entropy =random_get_entropy ();unsigned long flags; -if (crng_init ==0 && size) -crng_pre_init_inject (buf, size, false); -spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (&entropy,sizeof (entropy));_mix_pool_bytes (buf, size);
@@ -1139,12 +1114,6 @@ void rand_initialize_disk(struct gendiskvoid add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy) { -if (unlikely (crng_init ==0 && entropy <POOL_MIN_BITS )) { -crng_pre_init_inject (buffer, count, true); -mix_pool_bytes (buffer, count); -return ; - } -/* * Throttle writing if we're above the trickle threshold. * We'll be woken up again once below POOL_MIN_BITS, when
@@ -1152,7 +1121,7 @@ void add_hwgenerator_randomness(const vo* CRNG_RESEED_INTERVAL has elapsed. */ wait_event_interruptible_timeout (random_write_wait, - !system_wq ||kthread_should_stop () || +kthread_should_stop () || input_pool.entropy_count <POOL_MIN_BITS ,CRNG_RESEED_INTERVAL );mix_pool_bytes (buffer, count);
@@ -1161,17 +1130,14 @@ void add_hwgenerator_randomness(const voEXPORT_SYMBOL_GPL (add_hwgenerator_randomness);/* -* Handle random seed passed by bootloader. -* If the seed is trustworthy, it would be regarded as hardware RNGs. Otherwise -* it would be regarded as device data. -* The decision is controlled by CONFIG_RANDOM_TRUST_BOOTLOADER. +* Handle random seed passed by bootloader, and credit it if +* CONFIG_RANDOM_TRUST_BOOTLOADER is set. */ void add_bootloader_randomness (const void *buf,size_t size) { +mix_pool_bytes (buf, size);if (trust_bootloader) -add_hwgenerator_randomness (buf, size, size *8 ); -else -add_device_randomness (buf, size); +credit_entropy_bits (size *8 ); }EXPORT_SYMBOL_GPL (add_bootloader_randomness);
@@ -1271,13 +1237,8 @@ static void mix_interrupt_randomness(str fast_pool->last = jiffies;local_irq_enable (); -if (unlikely (crng_init ==0 )) { -crng_pre_init_inject (pool,sizeof (pool), true); -mix_pool_bytes (pool,sizeof (pool)); - }else { -mix_pool_bytes (pool,sizeof (pool)); -credit_entropy_bits (1 ); - } +mix_pool_bytes (pool,sizeof (pool)); +credit_entropy_bits (1 );memzero_explicit (pool,sizeof (pool)); }
@@ -1299,8 +1260,7 @@ void add_interrupt_randomness(int irq)if (new_count &MIX_INFLIGHT )return ; -if (new_count <64 && (!time_is_before_jiffies (fast_pool->last +HZ ) || -unlikely (crng_init ==0 ))) +if (new_count <64 && !time_is_before_jiffies (fast_pool->last +HZ ))return ;if (unlikely (!fast_pool->mix.func))
Greg Kroah-Hartman
maintainerPATCH 195/264 random: do not pretend to handle premature next security model
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit e85c0fc1d94c52483a603651748d4c76d6aa1c6b upstream.
Per the thread linked below, "premature next" is not considered to be a realistic threat model, and leads to more serious security problems.
"Premature next" is the scenario in which:
- Attacker compromises the current state of a fully initialized RNG via some kind of infoleak.
- New bits of entropy are added directly to the key used to generate the /dev/urandom stream, without any buffering or pooling.
- Attacker then, somehow having read access to /dev/urandom, samples RNG output and brute forces the individual new bits that were added.
- Result: the RNG never "recovers" from the initial compromise, a so-called violation of what academics term "post-compromise security".
The usual solutions to this involve some form of delaying when entropy gets mixed into the crng. With Fortuna, this involves multiple input buckets. With what the Linux RNG was trying to do prior, this involves entropy estimation.
However, by delaying when entropy gets mixed in, it also means that RNG compromises are extremely dangerous during the window of time before the RNG has gathered enough entropy, during which time nonces may become predictable (or repeated), ephemeral keys may not be secret, and so forth. Moreover, it's unclear how realistic "premature next" is from an attack perspective, if these attacks even make sense in practice.
Put together -- and discussed in more detail in the thread below -- these constitute grounds for just doing away with the current code that pretends to handle premature next. I say "pretends" because it wasn't doing an especially great job at it either; should we change our mind about this direction, we would probably implement Fortuna to "fix" the "problem", in which case, removing the pretend solution still makes sense.
This also reduces the crng reseed period from 5 minutes down to 1 minute. The rationale from the thread might lead us toward reducing that even further in the future (or even eliminating it), but that remains a topic of a future commit.
At a high level, this patch changes semantics from:
Before: Seed for the first time after 256 "bits" of estimated entropy have been accumulated since the system booted. Thereafter, reseed once every five minutes, but only if 256 new "bits" have been accumulated since the last reseeding.
After: Seed for the first time after 256 "bits" of estimated entropy have been accumulated since the system booted. Thereafter, reseed once every minute.
Most of this patch is renaming and removing: POOL_MIN_BITS becomes POOL_INIT_BITS, credit_entropy_bits() becomes credit_init_bits(), crng_reseed() loses its "force" parameter since it's now always true, the drain_entropy() function no longer has any use so it's removed, entropy estimation is skipped if we've already init'd, the various notifiers for "low on entropy" are now only active prior to init, and finally, some documentation comments are cleaned up here and there.
--- drivers/char/random.c | 174 +++++++++++++++++--------------------------------- 1 file changed, 62 insertions(+), 112 deletions(-)
drivers/char/random.c +62 -112
@@ -15,14 +15,12 @@* - Sysctl interface. * * The high level overview is that there is one input pool, into which -* various pieces of data are hashed. 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 and credit it. There is currently no Fortuna-like scheduler -* involved, which can lead to malicious entropy sources causing a premature -* reseed, and the entropy estimates are, at best, conservative guesses. +* 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
@@ -234,7 +232,10 @@ static void _warn_unseeded_randomness(co* *********************************************************************/ -enum {CRNG_RESEED_INTERVAL =300 *HZ }; +enum { +CRNG_RESEED_START_INTERVAL =HZ , +CRNG_RESEED_INTERVAL =60 *HZ +}; static struct { u8 key[CHACHA20_KEY_SIZE] __aligned(__alignof__(long));
@@ -254,16 +255,10 @@ static DEFINE_PER_CPU(struct crng, crngs .generation = ULONG_MAX }; -/* Used by crng_reseed() to extract a new seed from the input pool. */ -static bool drain_entropy (void *buf,size_t nbytes); -/* Used by crng_make_state() to extract a new seed when crng_init==0. */ +/* 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 nbytes); -/* -* This extracts a new crng key from the input pool, but only if there is a -* sufficient amount of entropy available, in order to mitigate bruteforcing -* of newly added bits. -*/ +/* This extracts a new crng key from the input pool. */ static void crng_reseed (void ) {unsigned long flags;
@@ -271,9 +266,7 @@ static void crng_reseed(void)u8 key[CHACHA20_KEY_SIZE ];bool finalize_init = false; -/* Only reseed if we can, to prevent brute forcing a small amount of new bits. */ -if (!drain_entropy (key,sizeof (key))) -return ; +extract_entropy (key,sizeof (key));/* * We copy the new key into the base_crng, overwriting the old one,
@@ -345,10 +338,10 @@ static void crng_fast_key_erasure(u8 key }/* -* Return whether the crng seed is considered to be sufficiently -* old that a reseeding might be attempted. This happens if the last -* reseeding was CRNG_RESEED_INTERVAL ago, or during early boot, at -* an interval proportional to the uptime. +* Return whether the crng seed is considered to be sufficiently old +* that a reseeding is needed. This happens if the last reseeding +* was CRNG_RESEED_INTERVAL ago, or during early boot, at an interval +* proportional to the uptime. */ static bool crng_has_old_seed (void ) {
@@ -360,7 +353,7 @@ static bool crng_has_old_seed(void)if (uptime >=CRNG_RESEED_INTERVAL /HZ *2 )WRITE_ONCE (early_boot, false);else - interval = max_t(unsigned int, 5 * HZ, + interval = max_t(unsigned int, CRNG_RESEED_START_INTERVAL, (unsigned int )uptime /2 *HZ ); }return time_after (jiffies,READ_ONCE (base_crng.birth) + interval);
@@ -402,8 +395,8 @@ static void crng_make_state(u32 chacha_s }/* -* If the base_crng is old enough, we try to reseed, which in turn -* bumps the generation counter that we check below. +* If the base_crng is old enough, we reseed, which in turn bumps the +* generation counter that we check below. */ if (unlikely (crng_has_old_seed ()))crng_reseed ();
@@ -732,30 +725,24 @@ EXPORT_SYMBOL(get_random_bytes_arch);* * After which, if added entropy should be credited: * -* static void credit_entropy_bits(size_t nbits) +* static void credit_init_bits(size_t nbits) * -* Finally, extract entropy via these two, with the latter one -* setting the entropy count to zero and extracting only if there -* is POOL_MIN_BITS entropy credited prior: +* Finally, extract entropy via: * * static void extract_entropy(void *buf, size_t nbytes) -* static bool drain_entropy(void *buf, size_t nbytes) * **********************************************************************/ enum {POOL_BITS =BLAKE2S_HASH_SIZE *8 , -POOL_MIN_BITS =POOL_BITS ,/* No point in settling for less. */ -POOL_FAST_INIT_BITS =POOL_MIN_BITS /2 +POOL_INIT_BITS =POOL_BITS ,/* No point in settling for less. */ +POOL_FAST_INIT_BITS =POOL_INIT_BITS /2 }; -/* For notifying userspace should write into /dev/random. */ -static DECLARE_WAIT_QUEUE_HEAD (random_write_wait); -static struct {struct blake2s_state hash;spinlock_t lock; -unsigned int entropy_count; +unsigned int init_bits; } input_pool = { .hash.h = {BLAKE2S_IV0 ^ (0x01010000 |BLAKE2S_HASH_SIZE ),BLAKE2S_IV1 ,BLAKE2S_IV2 ,BLAKE2S_IV3 ,BLAKE2S_IV4 ,
@@ -770,9 +757,9 @@ static void _mix_pool_bytes(const void * }/* -* This function adds bytes into the entropy "pool". It does not -* update the entropy estimate. The caller should call -* credit_entropy_bits if this is appropriate. +* This function adds bytes into the input pool. It does not +* update the initialization bit counter; the caller should call +* credit_init_bits if this is appropriate. */ static void mix_pool_bytes (const void *in,size_t nbytes) {
@@ -829,43 +816,24 @@ static void extract_entropy(void *buf, smemzero_explicit (&block,sizeof (block)); } -/* -* First we make sure we have POOL_MIN_BITS of entropy in the pool, and then we -* set the entropy count to zero (but don't actually touch any data). Only then -* can we extract a new key with extract_entropy(). -*/ -static bool drain_entropy (void *buf,size_t nbytes) -{ -unsigned int entropy_count; -do { - entropy_count =READ_ONCE (input_pool.entropy_count); -if (entropy_count <POOL_MIN_BITS ) -return false; - }while (cmpxchg (&input_pool.entropy_count, entropy_count,0 ) != entropy_count); -extract_entropy (buf, nbytes); -wake_up_interruptible (&random_write_wait); -kill_fasync (&fasync,SIGIO ,POLL_OUT ); -return true; -} - -static void credit_entropy_bits (size_t nbits) +static void credit_init_bits (size_t nbits) { -unsigned int entropy_count, orig, add; +unsigned int init_bits, orig, add;unsigned long flags; -if (!nbits) +if (crng_ready () || !nbits)return ; add =min_t (size_t, nbits,POOL_BITS );do { - orig =READ_ONCE (input_pool.entropy_count); - entropy_count = min_t(unsigned int, POOL_BITS, orig + add); - }while (cmpxchg (&input_pool.entropy_count, orig, entropy_count) != orig); + orig =READ_ONCE (input_pool.init_bits); + init_bits = min_t(unsigned int, POOL_BITS, orig + add); + }while (cmpxchg (&input_pool.init_bits, orig, init_bits) != orig); -if (!crng_ready () && entropy_count >=POOL_MIN_BITS ) +if (!crng_ready () && init_bits >=POOL_INIT_BITS )crng_reseed (); -else if (unlikely (crng_init ==0 && entropy_count >=POOL_FAST_INIT_BITS )) { +else if (unlikely (crng_init ==0 && init_bits >=POOL_FAST_INIT_BITS )) {spin_lock_irqsave (&base_crng.lock, flags);if (crng_init ==0 ) {extract_entropy (base_crng.key,sizeof (base_crng.key));
@@ -971,13 +939,10 @@ int __init rand_initialize(void)_mix_pool_bytes (&now,sizeof (now));_mix_pool_bytes (utsname (),sizeof (*(utsname ()))); -extract_entropy (base_crng.key,sizeof (base_crng.key)); - ++base_crng.generation; - -if (arch_init && trust_cpu && !crng_ready ()) { - crng_init =2 ; -pr_notice ("crng init done (trusting CPU's manufacturer)\n" ); - } +if (crng_ready ()) +crng_reseed (); +else if (arch_init && trust_cpu) +credit_init_bits (BLAKE2S_BLOCK_SIZE *8 );if (ratelimit_disable) { urandom_warning.interval =0 ;
@@ -1031,6 +996,9 @@ static void add_timer_randomness(struct_mix_pool_bytes (&num,sizeof (num));spin_unlock_irqrestore (&input_pool.lock, flags); +if (crng_ready ()) +return ; +/* * Calculate number of bits of randomness we probably added. * We take into account the first, second and third-order deltas
@@ -1061,7 +1029,7 @@ static void add_timer_randomness(struct* Round down by 1 bit on general principles, * and limit entropy estimate to 12 bits. */ - credit_entropy_bits(min_t(unsigned int, fls(delta >> 1), 11)); + credit_init_bits(min_t(unsigned int, fls(delta >> 1), 11)); } void add_input_randomness(unsigned int type, unsigned int code,
@@ -1114,18 +1082,15 @@ void rand_initialize_disk(struct gendiskvoid add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy) { +mix_pool_bytes (buffer, count); +credit_init_bits (entropy); +/* -* Throttle writing if we're above the trickle threshold. -* We'll be woken up again once below POOL_MIN_BITS, when -* the calling thread is about to terminate, or once -* CRNG_RESEED_INTERVAL has elapsed. +* Throttle writing to once every CRNG_RESEED_INTERVAL, unless +* we're not yet initialized. */ -wait_event_interruptible_timeout (random_write_wait, -kthread_should_stop () || - input_pool.entropy_count <POOL_MIN_BITS , -CRNG_RESEED_INTERVAL ); -mix_pool_bytes (buffer, count); -credit_entropy_bits (entropy); +if (!kthread_should_stop () &&crng_ready ()) +schedule_timeout_interruptible (CRNG_RESEED_INTERVAL ); }EXPORT_SYMBOL_GPL (add_hwgenerator_randomness);
@@ -1137,7 +1102,7 @@ void add_bootloader_randomness(const voi {mix_pool_bytes (buf, size);if (trust_bootloader) -credit_entropy_bits (size *8 ); +credit_init_bits (size *8 ); }EXPORT_SYMBOL_GPL (add_bootloader_randomness);
@@ -1238,7 +1203,7 @@ static void mix_interrupt_randomness(strlocal_irq_enable ();mix_pool_bytes (pool,sizeof (pool)); -credit_entropy_bits (1 ); +credit_init_bits (1 );memzero_explicit (pool,sizeof (pool)); }
@@ -1285,7 +1250,7 @@ EXPORT_SYMBOL_GPL(add_interrupt_randomne*/ static void entropy_timer (unsigned long data) { -credit_entropy_bits (1 ); +credit_init_bits (1 ); }/*
@@ -1378,16 +1343,8 @@ SYSCALL_DEFINE3(getrandom, char __user *static unsigned int random_poll (struct file *file,poll_table *wait) { -unsigned int mask; -poll_wait (file, &crng_init_wait, wait); -poll_wait (file, &random_write_wait, wait); - mask =0 ; -if (crng_ready ()) - mask |=POLLIN |POLLRDNORM ; -if (input_pool.entropy_count <POOL_MIN_BITS ) - mask |=POLLOUT |POLLWRNORM ; -return mask; +return crng_ready () ?POLLIN |POLLRDNORM :POLLOUT |POLLWRNORM ; }static int write_pool (const char __user *ubuf,size_t count)
@@ -1460,7 +1417,7 @@ static long random_ioctl(struct file *f,switch (cmd) {case RNDGETENTCNT :/* Inherently racy, no point locking. */ -if (put_user (input_pool.entropy_count, p)) +if (put_user (input_pool.init_bits, p))return -EFAULT ;return 0 ;case RNDADDTOENTCNT :
@@ -1470,7 +1427,7 @@ static long random_ioctl(struct file *f,return -EFAULT ;if (ent_count <0 )return -EINVAL ; -credit_entropy_bits (ent_count); +credit_init_bits (ent_count);return 0 ;case RNDADDENTROPY :if (!capable (CAP_SYS_ADMIN ))
@@ -1484,20 +1441,13 @@ static long random_ioctl(struct file *f, retval =write_pool ((const char __user *)p, size);if (retval <0 )return retval; -credit_entropy_bits (ent_count); +credit_init_bits (ent_count);return 0 ;case RNDZAPENTCNT :case RNDCLEARPOOL : -/* -* Clear the entropy pool counters. We no longer clear -* the entropy pool, as that's silly. -*/ +/* No longer has any effect. */ if (!capable (CAP_SYS_ADMIN ))return -EPERM ; -if (xchg (&input_pool.entropy_count,0 ) >=POOL_MIN_BITS ) { -wake_up_interruptible (&random_write_wait); -kill_fasync (&fasync,SIGIO ,POLL_OUT ); - }return 0 ;case RNDRESEEDCRNG :if (!capable (CAP_SYS_ADMIN ))
@@ -1554,7 +1504,7 @@ const struct file_operations urandom_fop* * - write_wakeup_threshold - the amount of entropy in the input pool * below which write polls to /dev/random will unblock, requesting -* more entropy, tied to the POOL_MIN_BITS constant. It is writable +* more entropy, tied to the POOL_INIT_BITS constant. It is writable * to avoid breaking old userspaces, but writing to it does not * change any behavior of the RNG. *
@@ -1569,7 +1519,7 @@ const struct file_operations urandom_fop#include <linux/sysctl.h> static int sysctl_random_min_urandom_seed =CRNG_RESEED_INTERVAL /HZ ; -static int sysctl_random_write_wakeup_bits =POOL_MIN_BITS ; +static int sysctl_random_write_wakeup_bits =POOL_INIT_BITS ;static int sysctl_poolsize =POOL_BITS ;static u8 sysctl_bootid[UUID_SIZE ];
@@ -1626,7 +1576,7 @@ struct ctl_table random_table[] = { }, { .procname = "entropy_avail", - .data = &input_pool.entropy_count, + .data = &input_pool.init_bits, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec,
Greg Kroah-Hartman
maintainerPATCH 196/264 random: order timer entropy functions below interrupt functions
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit a4b5c26b79ffdfcfb816c198f2fc2b1e7b5b580f upstream.
There are no code changes here; this is just a reordering of functions, so that in subsequent commits, the timer entropy functions can call into the interrupt ones.
--- drivers/char/random.c | 238 +++++++++++++++++++++++++------------------------- 1 file changed, 119 insertions(+), 119 deletions(-)
drivers/char/random.c +119 -119
@@ -852,13 +852,13 @@ static void credit_init_bits(size_t nbit* the above entropy accumulation routines: * * void add_device_randomness(const void *buf, size_t size); -* void add_input_randomness(unsigned int type, unsigned int code, -* unsigned int value); -* void add_disk_randomness(struct gendisk *disk); * void add_hwgenerator_randomness(const void *buffer, size_t count, * size_t entropy); * void add_bootloader_randomness(const void *buf, size_t size); * void add_interrupt_randomness(int irq); +* void add_input_randomness(unsigned int type, unsigned int code, +* unsigned int value); +* void add_disk_randomness(struct gendisk *disk); * * add_device_randomness() adds data to the input pool that * is likely to differ between two devices (or possibly even per boot).
@@ -868,19 +868,6 @@ static void credit_init_bits(size_t nbit* that might otherwise be identical and have very little entropy * available to them (particularly common in the embedded world). * -* add_input_randomness() uses the input layer interrupt timing, as well -* as the event type information from the hardware. -* -* add_disk_randomness() uses what amounts to the seek time of block -* layer request events, on a per-disk_devt basis, as input to the -* entropy pool. Note that high-speed solid state drives with very low -* seek times do not make for good sources of entropy, as their seek -* times are usually fairly consistent. -* -* The above two routines try to estimate how many bits of entropy -* to credit. They do this by keeping track of the first and second -* order deltas of the event timings. -* * add_hwgenerator_randomness() is for true hardware RNGs, and will credit * entropy as specified by the caller. If the entropy pool is full it will * block until more entropy is needed.
@@ -894,6 +881,19 @@ static void credit_init_bits(size_t nbit* as inputs, it feeds the input pool roughly once a second or after 64 * interrupts, crediting 1 bit of entropy for whichever comes first. * +* add_input_randomness() uses the input layer interrupt timing, as well +* as the event type information from the hardware. +* +* add_disk_randomness() uses what amounts to the seek time of block +* layer request events, on a per-disk_devt basis, as input to the +* entropy pool. Note that high-speed solid state drives with very low +* seek times do not make for good sources of entropy, as their seek +* times are usually fairly consistent. +* +* The last two routines try to estimate how many bits of entropy +* to credit. They do this by keeping track of the first and second +* order deltas of the event timings. +* **********************************************************************/ static bool trust_cpu__ro_after_init =IS_ENABLED (CONFIG_RANDOM_TRUST_CPU );
@@ -971,109 +971,6 @@ void add_device_randomness(const void *b }EXPORT_SYMBOL (add_device_randomness); -/* There is one of these per entropy source */ -struct timer_rand_state { -unsigned long last_time; -long last_delta, last_delta2; -}; - -/* -* This function adds entropy to the entropy "pool" by using timing -* delays. It uses the timer_rand_state structure to make an estimate -* of how many bits of entropy this call has added to the pool. -* -* The number "num" is also added to the pool - it should somehow describe -* the type of event which just happened. This is currently 0-255 for -* keyboard scan codes, and 256 upwards for interrupts. -*/ -static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) -{ -unsigned long entropy =random_get_entropy (), now = jiffies, flags; -long delta, delta2, delta3; - -spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (&entropy,sizeof (entropy)); -_mix_pool_bytes (&num,sizeof (num)); -spin_unlock_irqrestore (&input_pool.lock, flags); - -if (crng_ready ()) -return ; - -/* -* Calculate number of bits of randomness we probably added. -* We take into account the first, second and third-order deltas -* in order to make our estimate. -*/ - delta = now -READ_ONCE (state->last_time); -WRITE_ONCE (state->last_time, now); - - delta2 = delta - state->last_delta; - state->last_delta = delta; - - delta3 = delta2 - state->last_delta2; - state->last_delta2 = delta2; - -if (delta <0 ) - delta = -delta; -if (delta2 <0 ) - delta2 = -delta2; -if (delta3 <0 ) - delta3 = -delta3; -if (delta > delta2) - delta = delta2; -if (delta > delta3) - delta = delta3; - -/* -* delta is now minimum absolute delta. -* Round down by 1 bit on general principles, -* and limit entropy estimate to 12 bits. -*/ - credit_init_bits(min_t(unsigned int, fls(delta >> 1), 11)); -} - -void add_input_randomness (unsigned int type,unsigned int code, -unsigned int value) -{ -static unsigned char last_value; -static struct timer_rand_state input_timer_state = {INITIAL_JIFFIES }; - -/* Ignore autorepeat and the like. */ -if (value == last_value) -return ; - - last_value = value; -add_timer_randomness (&input_timer_state, - (type <<4 ) ^ code ^ (code >>4 ) ^ value); -} -EXPORT_SYMBOL_GPL (add_input_randomness); - -#ifdef CONFIG_BLOCK -void add_disk_randomness (struct gendisk *disk) -{ -if (!disk || !disk->random) -return ; -/* First major is 1, so we get >= 0x200 here. */ -add_timer_randomness (disk->random,0x100 +disk_devt (disk)); -} -EXPORT_SYMBOL_GPL (add_disk_randomness); - -void rand_initialize_disk (struct gendisk *disk) -{ -struct timer_rand_state *state; - -/* -* If kzalloc returns null, we just won't use that entropy -* source. -*/ - state =kzalloc (sizeof (struct timer_rand_state ),GFP_KERNEL ); -if (state) { - state->last_time =INITIAL_JIFFIES ; - disk->random = state; - } -} -#endif -/* * Interface for in-kernel drivers of true hardware RNGs. * Those devices may produce endless random bits and will be throttled
@@ -1235,6 +1132,109 @@ void add_interrupt_randomness(int irq) }EXPORT_SYMBOL_GPL (add_interrupt_randomness); +/* There is one of these per entropy source */ +struct timer_rand_state { +unsigned long last_time; +long last_delta, last_delta2; +}; + +/* +* This function adds entropy to the entropy "pool" by using timing +* delays. It uses the timer_rand_state structure to make an estimate +* of how many bits of entropy this call has added to the pool. +* +* The number "num" is also added to the pool - it should somehow describe +* the type of event which just happened. This is currently 0-255 for +* keyboard scan codes, and 256 upwards for interrupts. +*/ +static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) +{ +unsigned long entropy =random_get_entropy (), now = jiffies, flags; +long delta, delta2, delta3; + +spin_lock_irqsave (&input_pool.lock, flags); +_mix_pool_bytes (&entropy,sizeof (entropy)); +_mix_pool_bytes (&num,sizeof (num)); +spin_unlock_irqrestore (&input_pool.lock, flags); + +if (crng_ready ()) +return ; + +/* +* Calculate number of bits of randomness we probably added. +* We take into account the first, second and third-order deltas +* in order to make our estimate. +*/ + delta = now -READ_ONCE (state->last_time); +WRITE_ONCE (state->last_time, now); + + delta2 = delta -READ_ONCE (state->last_delta); +WRITE_ONCE (state->last_delta, delta); + + delta3 = delta2 -READ_ONCE (state->last_delta2); +WRITE_ONCE (state->last_delta2, delta2); + +if (delta <0 ) + delta = -delta; +if (delta2 <0 ) + delta2 = -delta2; +if (delta3 <0 ) + delta3 = -delta3; +if (delta > delta2) + delta = delta2; +if (delta > delta3) + delta = delta3; + +/* +* delta is now minimum absolute delta. +* Round down by 1 bit on general principles, +* and limit entropy estimate to 12 bits. +*/ + credit_init_bits(min_t(unsigned int, fls(delta >> 1), 11)); +} + +void add_input_randomness (unsigned int type,unsigned int code, +unsigned int value) +{ +static unsigned char last_value; +static struct timer_rand_state input_timer_state = {INITIAL_JIFFIES }; + +/* Ignore autorepeat and the like. */ +if (value == last_value) +return ; + + last_value = value; +add_timer_randomness (&input_timer_state, + (type <<4 ) ^ code ^ (code >>4 ) ^ value); +} +EXPORT_SYMBOL_GPL (add_input_randomness); + +#ifdef CONFIG_BLOCK +void add_disk_randomness (struct gendisk *disk) +{ +if (!disk || !disk->random) +return ; +/* First major is 1, so we get >= 0x200 here. */ +add_timer_randomness (disk->random,0x100 +disk_devt (disk)); +} +EXPORT_SYMBOL_GPL (add_disk_randomness); + +void rand_initialize_disk (struct gendisk *disk) +{ +struct timer_rand_state *state; + +/* +* If kzalloc returns null, we just won't use that entropy +* source. +*/ + state =kzalloc (sizeof (struct timer_rand_state ),GFP_KERNEL ); +if (state) { + state->last_time =INITIAL_JIFFIES ; + disk->random = state; + } +} +#endif +/* * Each time the timer fires, we expect that we got an unpredictable * jump in the cycle counter. Even if the timer is running on another
Greg Kroah-Hartman
maintainerPATCH 197/264 random: do not use input pool from hard IRQs
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit e3e33fc2ea7fcefd0d761db9d6219f83b4248f5c upstream.
Years ago, a separate fast pool was added for interrupts, so that the cost associated with taking the input pool spinlocks and mixing into it would be avoided in places where latency is critical. However, one oversight was that add_input_randomness() and add_disk_randomness() still sometimes are called directly from the interrupt handler, rather than being deferred to a thread. This means that some unlucky interrupts will be caught doing a blake2s_compress() call and potentially spinning on input_pool.lock, which can also be taken by unprivileged users by writing into /dev/urandom.
In order to fix this, add_timer_randomness() now checks whether it is being called from a hard IRQ and if so, just mixes into the per-cpu IRQ fast pool using fast_mix(), which is much faster and can be done lock-free. A nice consequence of this, as well, is that it means hard IRQ context FPU support is likely no longer useful.
The entropy estimation algorithm used by add_timer_randomness() is also somewhat different than the one used for add_interrupt_randomness(). The former looks at deltas of deltas of deltas, while the latter just waits for 64 interrupts for one bit or for one second since the last bit. In order to bridge these, and since add_interrupt_randomness() runs after an add_timer_randomness() that's called from hard IRQ, we add to the fast pool credit the related amount, and then subtract one to account for add_interrupt_randomness()'s contribution.
A downside of this, however, is that the num argument is potentially attacker controlled, which puts a bit more pressure on the fast_mix() sponge to do more than it's really intended to do. As a mitigating factor, the first 96 bits of input aren't attacker controlled (a cycle counter followed by zeros), which means it's essentially two rounds of siphash rather than one, which is somewhat better. It's also not that much different from add_interrupt_randomness()'s use of the irq stack instruction pointer register.
--- drivers/char/random.c | 51 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 15 deletions(-)
drivers/char/random.c +36 -15
@@ -1082,6 +1082,7 @@ static void mix_interrupt_randomness(str* we don't wind up "losing" some. */ unsigned long pool[2 ]; +unsigned int count;/* Check to see if we're running on the wrong CPU due to hotplug. */ local_irq_disable ();
@@ -1095,12 +1096,13 @@ static void mix_interrupt_randomness(str* consistent view, before we reenable irqs again. */ memcpy (pool, fast_pool->pool,sizeof (pool)); + count = fast_pool->count; fast_pool->count =0 ; fast_pool->last = jiffies;local_irq_enable ();mix_pool_bytes (pool,sizeof (pool)); -credit_init_bits (1 ); +credit_init_bits (max (1u , (count &U16_MAX ) /64 ));memzero_explicit (pool,sizeof (pool)); }
@@ -1140,22 +1142,30 @@ struct timer_rand_state {/* * This function adds entropy to the entropy "pool" by using timing -* delays. It uses the timer_rand_state structure to make an estimate -* of how many bits of entropy this call has added to the pool. -* -* The number "num" is also added to the pool - it should somehow describe -* the type of event which just happened. This is currently 0-255 for -* keyboard scan codes, and 256 upwards for interrupts. +* delays. It uses the timer_rand_state structure to make an estimate +* of how many bits of entropy this call has added to the pool. The +* value "num" is also added to the pool; it should somehow describe +* the type of event that just happened. */ static void add_timer_randomness (struct timer_rand_state *state,unsigned int num) {unsigned long entropy =random_get_entropy (), now = jiffies, flags;long delta, delta2, delta3; +unsigned int bits; -spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (&entropy,sizeof (entropy)); -_mix_pool_bytes (&num,sizeof (num)); -spin_unlock_irqrestore (&input_pool.lock, flags); +/* +* If we're in a hard IRQ, add_interrupt_randomness() will be called +* sometime after, so mix into the fast pool. +*/ +if (in_irq ()) { +fast_mix (this_cpu_ptr (&irq_randomness)->pool, + (unsigned long [2 ]){ entropy, num }); + }else { +spin_lock_irqsave (&input_pool.lock, flags); +_mix_pool_bytes (&entropy,sizeof (entropy)); +_mix_pool_bytes (&num,sizeof (num)); +spin_unlock_irqrestore (&input_pool.lock, flags); + }if (crng_ready ())return ;
@@ -1186,11 +1196,22 @@ static void add_timer_randomness(struct delta = delta3;/* -* delta is now minimum absolute delta. -* Round down by 1 bit on general principles, -* and limit entropy estimate to 12 bits. +* delta is now minimum absolute delta. Round down by 1 bit +* on general principles, and limit entropy estimate to 11 bits. +*/ + bits =min (fls (delta >>1 ),11 ); + +/* +* As mentioned above, if we're in a hard IRQ, add_interrupt_randomness() +* will run after this, which uses a different crediting scheme of 1 bit +* per every 64 interrupts. In order to let that function do accounting +* close to the one in this function, we credit a full 64/64 bit per bit, +* and then subtract one to account for the extra one added. */ - credit_init_bits(min_t(unsigned int, fls(delta >> 1), 11)); +if (in_irq ()) +this_cpu_ptr (&irq_randomness)->count +=max (1u , bits *64 ) -1 ; +else +credit_init_bits (bits); } void add_input_randomness(unsigned int type, unsigned int code,
Greg Kroah-Hartman
maintainerPATCH 198/264 random: help compiler out with fast_mix() by using simpler arguments
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 791332b3cbb080510954a4c152ce02af8832eac9 upstream.
Now that fast_mix() has more than one caller, gcc no longer inlines it. That's fine. But it also doesn't handle the compound literal argument we pass it very efficiently, nor does it handle the loop as well as it could. So just expand the code to spell out this function so that it generates the same code as it did before. Performance-wise, this now behaves as it did before the last commit. The difference in actual code size on x86 is 45 bytes, which is less than a cache line.
--- drivers/char/random.c | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-)
drivers/char/random.c +23 -21
@@ -1027,25 +1027,30 @@ static DEFINE_PER_CPU(struct fast_pool,* and therefore this has no security on its own. s represents the * four-word SipHash state, while v represents a two-word input. */ -static void fast_mix (unsigned long s[4 ],const unsigned long v[2 ]) +static void fast_mix (unsigned long s[4 ],unsigned long v1,unsigned long v2) { -size_t i; - -for (i =0 ; i <2 ; ++i) { - s[3 ] ^= v[i];#ifdef CONFIG_64BIT - s[0 ] += s[1 ]; s[1 ] =rol64 (s[1 ],13 ); s[1 ] ^= s[0 ]; s[0 ] =rol64 (s[0 ],32 ); - s[2 ] += s[3 ]; s[3 ] =rol64 (s[3 ],16 ); s[3 ] ^= s[2 ]; - s[0 ] += s[3 ]; s[3 ] =rol64 (s[3 ],21 ); s[3 ] ^= s[0 ]; - s[2 ] += s[1 ]; s[1 ] =rol64 (s[1 ],17 ); s[1 ] ^= s[2 ]; s[2 ] =rol64 (s[2 ],32 ); +#define PERM () do { \ + s[0] += s[1]; s[1] = rol64(s[1], 13); s[1] ^= s[0]; s[0] = rol64(s[0], 32); \ + s[2] += s[3]; s[3] = rol64(s[3], 16); s[3] ^= s[2]; \ + s[0] += s[3]; s[3] = rol64(s[3], 21); s[3] ^= s[0]; \ + s[2] += s[1]; s[1] = rol64(s[1], 17); s[1] ^= s[2]; s[2] = rol64(s[2], 32); \ +} while (0)#else - s[0 ] += s[1 ]; s[1 ] =rol32 (s[1 ],5 ); s[1 ] ^= s[0 ]; s[0 ] =rol32 (s[0 ],16 ); - s[2 ] += s[3 ]; s[3 ] =rol32 (s[3 ],8 ); s[3 ] ^= s[2 ]; - s[0 ] += s[3 ]; s[3 ] =rol32 (s[3 ],7 ); s[3 ] ^= s[0 ]; - s[2 ] += s[1 ]; s[1 ] =rol32 (s[1 ],13 ); s[1 ] ^= s[2 ]; s[2 ] =rol32 (s[2 ],16 ); +#define PERM () do { \ + s[0] += s[1]; s[1] = rol32(s[1], 5); s[1] ^= s[0]; s[0] = rol32(s[0], 16); \ + s[2] += s[3]; s[3] = rol32(s[3], 8); s[3] ^= s[2]; \ + s[0] += s[3]; s[3] = rol32(s[3], 7); s[3] ^= s[0]; \ + s[2] += s[1]; s[1] = rol32(s[1], 13); s[1] ^= s[2]; s[2] = rol32(s[2], 16); \ +} while (0)#endif - s[0 ] ^= v[i]; - } + + s[3 ] ^= v1; +PERM (); + s[0 ] ^= v1; + s[3 ] ^= v2; +PERM (); + s[0 ] ^= v2; }#ifdef CONFIG_SMP
@@ -1115,10 +1120,8 @@ void add_interrupt_randomness(int irq)struct pt_regs *regs =get_irq_regs ();unsigned int new_count; -fast_mix (fast_pool->pool, (unsigned long [2 ]){ - entropy, - (regs ?instruction_pointer (regs) : _RET_IP_) ^swab (irq) - }); +fast_mix (fast_pool->pool, entropy, + (regs ?instruction_pointer (regs) : _RET_IP_) ^swab (irq)); new_count = ++fast_pool->count;if (new_count &MIX_INFLIGHT )
@@ -1158,8 +1161,7 @@ static void add_timer_randomness(struct* sometime after, so mix into the fast pool. */ if (in_irq ()) { -fast_mix (this_cpu_ptr (&irq_randomness)->pool, - (unsigned long [2 ]){ entropy, num }); +fast_mix (this_cpu_ptr (&irq_randomness)->pool, entropy, num); }else {spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (&entropy,sizeof (entropy));
Greg Kroah-Hartman
maintainerPATCH 199/264 siphash: use one source of truth for siphash permutations
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit e73aaae2fa9024832e1f42e30c787c7baf61d014 upstream.
The SipHash family of permutations is currently used in three places:
- siphash.c itself, used in the ordinary way it was intended.
- random32.c, in a construction from an anonymous contributor.
- random.c, as part of its fast_mix function.
Each one of these places reinvents the wheel with the same C code, same rotation constants, and same symmetry-breaking constants.
This commit tidies things up a bit by placing macros for the permutations and constants into siphash.h, where each of the three .c users can access them. It also leaves a note dissuading more users of them from emerging.
--- drivers/char/random.c | 30 +++++++----------------------- include/linux/prandom.h | 23 +++++++---------------- include/linux/siphash.h | 28 ++++++++++++++++++++++++++++ lib/siphash.c | 32 ++++++++++---------------------- 4 files changed, 52 insertions(+), 61 deletions(-)
drivers/char/random.c +7 -23
@@ -51,6 +51,7 @@#include <linux/syscalls.h> #include <linux/completion.h> #include <linux/uuid.h> +#include <linux/siphash.h> #include <crypto/chacha20.h> #include <crypto/blake2s.h> #include <asm/processor.h>
@@ -1012,12 +1013,11 @@ struct fast_pool { static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {#ifdef CONFIG_64BIT -/* SipHash constants */ - .pool = { 0x736f6d6570736575UL, 0x646f72616e646f6dUL, - 0x6c7967656e657261UL, 0x7465646279746573UL } +#define FASTMIX_PERM SIPHASH_PERMUTATION + .pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 }#else -/* HalfSipHash constants */ - .pool = { 0, 0, 0x6c796765U, 0x74656462U } +#define FASTMIX_PERM HSIPHASH_PERMUTATION + .pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 }#endif };
@@ -1029,27 +1029,11 @@ static DEFINE_PER_CPU(struct fast_pool,*/ static void fast_mix (unsigned long s[4 ],unsigned long v1,unsigned long v2) { -#ifdef CONFIG_64BIT -#define PERM () do { \ - s[0] += s[1]; s[1] = rol64(s[1], 13); s[1] ^= s[0]; s[0] = rol64(s[0], 32); \ - s[2] += s[3]; s[3] = rol64(s[3], 16); s[3] ^= s[2]; \ - s[0] += s[3]; s[3] = rol64(s[3], 21); s[3] ^= s[0]; \ - s[2] += s[1]; s[1] = rol64(s[1], 17); s[1] ^= s[2]; s[2] = rol64(s[2], 32); \ -} while (0) -#else -#define PERM () do { \ - s[0] += s[1]; s[1] = rol32(s[1], 5); s[1] ^= s[0]; s[0] = rol32(s[0], 16); \ - s[2] += s[3]; s[3] = rol32(s[3], 8); s[3] ^= s[2]; \ - s[0] += s[3]; s[3] = rol32(s[3], 7); s[3] ^= s[0]; \ - s[2] += s[1]; s[1] = rol32(s[1], 13); s[1] ^= s[2]; s[2] = rol32(s[2], 16); \ -} while (0) -#endif - s[3 ] ^= v1; -PERM (); +FASTMIX_PERM (s[0 ], s[1 ], s[2 ], s[3 ]); s[0 ] ^= v1; s[3 ] ^= v2; -PERM (); +FASTMIX_PERM (s[0 ], s[1 ], s[2 ], s[3 ]); s[0 ] ^= v2; }
include/linux/prandom.h +7 -16
@@ -10,6 +10,7 @@#include <linux/types.h> #include <linux/percpu.h> +#include <linux/siphash.h> u32 prandom_u32 (void );void prandom_bytes (void *buf,size_t nbytes);
@@ -21,15 +22,10 @@ void prandom_reseed_late(void);* The core SipHash round function. Each line can be executed in * parallel given enough CPU resources. */ -#define PRND_SIPROUND (v0, v1, v2, v3) ( \ - v0 += v1, v1 = rol64(v1, 13), v2 += v3, v3 = rol64(v3, 16), \ - v1 ^= v0, v0 = rol64(v0, 32), v3 ^= v2, \ - v0 += v3, v3 = rol64(v3, 21), v2 += v1, v1 = rol64(v1, 17), \ - v3 ^= v0, v1 ^= v2, v2 = rol64(v2, 32) \ -) +#define PRND_SIPROUND (v0, v1, v2, v3) SIPHASH_PERMUTATION(v0, v1, v2, v3) -#define PRND_K0 (0x736f6d6570736575 ^ 0x6c7967656e657261) -#define PRND_K1 (0x646f72616e646f6d ^ 0x7465646279746573) +#define PRND_K0 (SIPHASH_CONST_0 ^ SIPHASH_CONST_2) +#define PRND_K1 (SIPHASH_CONST_1 ^ SIPHASH_CONST_3)#elif BITS_PER_LONG ==32 /*
@@ -37,14 +33,9 @@ void prandom_reseed_late(void);* This is weaker, but 32-bit machines are not used for high-traffic * applications, so there is less output for an attacker to analyze. */ -#define PRND_SIPROUND (v0, v1, v2, v3) ( \ - v0 += v1, v1 = rol32(v1, 5), v2 += v3, v3 = rol32(v3, 8), \ - v1 ^= v0, v0 = rol32(v0, 16), v3 ^= v2, \ - v0 += v3, v3 = rol32(v3, 7), v2 += v1, v1 = rol32(v1, 13), \ - v3 ^= v0, v1 ^= v2, v2 = rol32(v2, 16) \ -) -#define PRND_K0 0x6c796765 -#define PRND_K1 0x74656462 +#define PRND_SIPROUND (v0, v1, v2, v3) HSIPHASH_PERMUTATION(v0, v1, v2, v3) +#define PRND_K0 (HSIPHASH_CONST_0 ^ HSIPHASH_CONST_2) +#define PRND_K1 (HSIPHASH_CONST_1 ^ HSIPHASH_CONST_3)#else #error Unsupported BITS_PER_LONG
include/linux/siphash.h +28 -0
@@ -136,4 +136,32 @@ static inline u32 hsiphash(const void *d return ___hsiphash_aligned(data, len, key); } +/* +* These macros expose the raw SipHash and HalfSipHash permutations. +* Do not use them directly! If you think you have a use for them, +* be sure to CC the maintainer of this file explaining why. +*/ + +#define SIPHASH_PERMUTATION (a, b, c, d) ( \ + (a) += (b), (b) = rol64((b), 13), (b) ^= (a), (a) = rol64((a), 32), \ + (c) += (d), (d) = rol64((d), 16), (d) ^= (c), \ + (a) += (d), (d) = rol64((d), 21), (d) ^= (a), \ + (c) += (b), (b) = rol64((b), 17), (b) ^= (c), (c) = rol64((c), 32)) + +#define SIPHASH_CONST_0 0x736f6d6570736575ULL +#define SIPHASH_CONST_1 0x646f72616e646f6dULL +#define SIPHASH_CONST_2 0x6c7967656e657261ULL +#define SIPHASH_CONST_3 0x7465646279746573ULL + +#define HSIPHASH_PERMUTATION (a, b, c, d) ( \ + (a) += (b), (b) = rol32((b), 5), (b) ^= (a), (a) = rol32((a), 16), \ + (c) += (d), (d) = rol32((d), 8), (d) ^= (c), \ + (a) += (d), (d) = rol32((d), 7), (d) ^= (a), \ + (c) += (b), (b) = rol32((b), 13), (b) ^= (c), (c) = rol32((c), 16)) + +#define HSIPHASH_CONST_0 0U +#define HSIPHASH_CONST_1 0U +#define HSIPHASH_CONST_2 0x6c796765U +#define HSIPHASH_CONST_3 0x74656462U +#endif /* _LINUX_SIPHASH_H */
lib/siphash.c +10 -22
@@ -18,19 +18,13 @@#include <asm/word-at-a-time.h> #endif -#define SIPROUND \ - do { \ - v0 += v1; v1 = rol64(v1, 13); v1 ^= v0; v0 = rol64(v0, 32); \ - v2 += v3; v3 = rol64(v3, 16); v3 ^= v2; \ - v0 += v3; v3 = rol64(v3, 21); v3 ^= v0; \ - v2 += v1; v1 = rol64(v1, 17); v1 ^= v2; v2 = rol64(v2, 32); \ - } while (0) +#define SIPROUND SIPHASH_PERMUTATION(v0, v1, v2, v3)#define PREAMBLE (len) \ - u64 v0 = 0x736f6d6570736575ULL; \ - u64 v1 = 0x646f72616e646f6dULL; \ - u64 v2 = 0x6c7967656e657261ULL; \ - u64 v3 = 0x7465646279746573ULL; \ + u64 v0 = SIPHASH_CONST_0; \ + u64 v1 = SIPHASH_CONST_1; \ + u64 v2 = SIPHASH_CONST_2; \ + u64 v3 = SIPHASH_CONST_3; \ u64 b = ((u64)(len)) << 56; \ v3 ^= key->key[1]; \ v2 ^= key->key[0]; \
@@ -389,19 +383,13 @@ u32 hsiphash_4u32(const u32 first, const }EXPORT_SYMBOL (hsiphash_4u32);#else -#define HSIPROUND \ - do { \ - v0 += v1; v1 = rol32(v1, 5); v1 ^= v0; v0 = rol32(v0, 16); \ - v2 += v3; v3 = rol32(v3, 8); v3 ^= v2; \ - v0 += v3; v3 = rol32(v3, 7); v3 ^= v0; \ - v2 += v1; v1 = rol32(v1, 13); v1 ^= v2; v2 = rol32(v2, 16); \ - } while (0) +#define HSIPROUND HSIPHASH_PERMUTATION(v0, v1, v2, v3)#define HPREAMBLE (len) \ - u32 v0 = 0; \ - u32 v1 = 0; \ - u32 v2 = 0x6c796765U; \ - u32 v3 = 0x74656462U; \ + u32 v0 = HSIPHASH_CONST_0; \ + u32 v1 = HSIPHASH_CONST_1; \ + u32 v2 = HSIPHASH_CONST_2; \ + u32 v3 = HSIPHASH_CONST_3; \ u32 b = ((u32)(len)) << 24; \ v3 ^= key->key[1]; \ v2 ^= key->key[0]; \
Greg Kroah-Hartman
maintainerPATCH 200/264 random: use symbolic constants for crng_init states
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit e3d2c5e79a999aa4e7d6f0127e16d3da5a4ff70d upstream.
crng_init represents a state machine, with three states, and various rules for transitions. For the longest time, we've been managing these with "0", "1", and "2", and expecting people to figure it out. To make the code more obvious, replace these with proper enum values representing the transition, and then redocument what each of these states mean.
--- drivers/char/random.c | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-)
drivers/char/random.c +19 -19
@@ -71,16 +71,16 @@*********************************************************************/ /* -* crng_init = 0 --> Uninitialized -* 1 --> Initialized -* 2 --> Initialized from input_pool -* * crng_init is protected by base_crng->lock, and only increases -* its value (from 0->1->2). +* its value (from empty->early->ready). */ -static int crng_init =0 ; -#define crng_ready () (likely(crng_init > 1)) -/* Various types of waiters for crng_init->2 transition. */ +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 =CRNG_EMPTY ; +#define crng_ready () (likely(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 DEFINE_SPINLOCK (random_ready_chain_lock);
@@ -283,7 +283,7 @@ static void crng_reseed(void)WRITE_ONCE (base_crng.generation, next_gen);WRITE_ONCE (base_crng.birth, jiffies);if (!crng_ready ()) { - crng_init =2 ; + crng_init =CRNG_READY ; finalize_init = true; }spin_unlock_irqrestore (&base_crng.lock, flags);
@@ -377,7 +377,7 @@ static void crng_make_state(u32 chacha_s* 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==0. +* when crng_init is CRNG_EMPTY. */ if (!crng_ready ()) {bool ready;
@@ -385,7 +385,7 @@ static void crng_make_state(u32 chacha_sspin_lock_irqsave (&base_crng.lock, flags); ready =crng_ready ();if (!ready) { -if (crng_init ==0 ) +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);
@@ -736,8 +736,8 @@ EXPORT_SYMBOL(get_random_bytes_arch);enum {POOL_BITS =BLAKE2S_HASH_SIZE *8 , -POOL_INIT_BITS =POOL_BITS ,/* No point in settling for less. */ -POOL_FAST_INIT_BITS =POOL_INIT_BITS /2 +POOL_READY_BITS =POOL_BITS ,/* When crng_init->CRNG_READY */ +POOL_EARLY_BITS =POOL_READY_BITS /2 /* When crng_init->CRNG_EARLY */ }; static struct {
@@ -832,13 +832,13 @@ static void credit_init_bits(size_t nbit init_bits = min_t(unsigned int, POOL_BITS, orig + add); }while (cmpxchg (&input_pool.init_bits, orig, init_bits) != orig); -if (!crng_ready () && init_bits >=POOL_INIT_BITS ) +if (!crng_ready () && init_bits >=POOL_READY_BITS )crng_reseed (); -else if (unlikely (crng_init ==0 && init_bits >=POOL_FAST_INIT_BITS )) { +else if (unlikely (crng_init ==CRNG_EMPTY && init_bits >=POOL_EARLY_BITS )) {spin_lock_irqsave (&base_crng.lock, flags); -if (crng_init ==0 ) { +if (crng_init ==CRNG_EMPTY ) {extract_entropy (base_crng.key,sizeof (base_crng.key)); - crng_init =1 ; + crng_init =CRNG_EARLY ; }spin_unlock_irqrestore (&base_crng.lock, flags); }
@@ -1511,7 +1511,7 @@ const struct file_operations urandom_fop* * - write_wakeup_threshold - the amount of entropy in the input pool * below which write polls to /dev/random will unblock, requesting -* more entropy, tied to the POOL_INIT_BITS constant. It is writable +* more entropy, tied to the POOL_READY_BITS constant. It is writable * to avoid breaking old userspaces, but writing to it does not * change any behavior of the RNG. *
@@ -1526,7 +1526,7 @@ const struct file_operations urandom_fop#include <linux/sysctl.h> static int sysctl_random_min_urandom_seed =CRNG_RESEED_INTERVAL /HZ ; -static int sysctl_random_write_wakeup_bits =POOL_INIT_BITS ; +static int sysctl_random_write_wakeup_bits =POOL_READY_BITS ;static int sysctl_poolsize =POOL_BITS ;static u8 sysctl_bootid[UUID_SIZE ];
Greg Kroah-Hartman
maintainerPATCH 201/264 random: avoid initializing twice in credit race
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit fed7ef061686cc813b1f3d8d0edc6c35b4d3537b upstream.
Since all changes of crng_init now go through credit_init_bits(), we can fix a long standing race in which two concurrent callers of credit_init_bits() have the new bit count >= some threshold, but are doing so with crng_init as a lower threshold, checked outside of a lock, resulting in crng_reseed() or similar being called twice.
In order to fix this, we can use the original cmpxchg value of the bit count, and only change crng_init when the bit count transitions from below a threshold to meeting the threshold.
--- drivers/char/random.c | 48 ++++++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 26 deletions(-)
drivers/char/random.c +22 -26
@@ -265,7 +265,6 @@ static void crng_reseed(void)unsigned long flags;unsigned long next_gen;u8 key[CHACHA20_KEY_SIZE ]; -bool finalize_init = false;extract_entropy (key,sizeof (key));
@@ -282,28 +281,10 @@ static void crng_reseed(void) ++next_gen;WRITE_ONCE (base_crng.generation, next_gen);WRITE_ONCE (base_crng.birth, jiffies); -if (!crng_ready ()) { +if (!crng_ready ()) crng_init =CRNG_READY ; - finalize_init = true; - }spin_unlock_irqrestore (&base_crng.lock, flags);memzero_explicit (key,sizeof (key)); -if (finalize_init) { -process_random_ready_list (); -wake_up_interruptible (&crng_init_wait); -kill_fasync (&fasync,SIGIO ,POLL_IN ); -pr_notice ("crng init done\n" ); -if (unseeded_warning.missed) { -pr_notice ("%d get_random_xx warning(s) missed due to ratelimiting\n" , - unseeded_warning.missed); - unseeded_warning.missed =0 ; - } -if (urandom_warning.missed) { -pr_notice ("%d urandom warning(s) missed due to ratelimiting\n" , - urandom_warning.missed); - urandom_warning.missed =0 ; - } - } }/*
@@ -819,7 +800,7 @@ static void extract_entropy(void *buf, sstatic void credit_init_bits (size_t nbits) { -unsigned int init_bits, orig, add; +unsigned int new, orig, add;unsigned long flags;if (crng_ready () || !nbits)
@@ -829,13 +810,28 @@ static void credit_init_bits(size_t nbitdo { orig =READ_ONCE (input_pool.init_bits); - init_bits = min_t(unsigned int, POOL_BITS, orig + add); - }while (cmpxchg (&input_pool.init_bits, orig, init_bits) != orig); + new = min_t(unsigned int, POOL_BITS, orig + add); + }while (cmpxchg (&input_pool.init_bits, orig, new) != orig); -if (!crng_ready () && init_bits >=POOL_READY_BITS ) -crng_reseed (); -else if (unlikely (crng_init ==CRNG_EMPTY && init_bits >=POOL_EARLY_BITS )) { +if (orig <POOL_READY_BITS && new >=POOL_READY_BITS ) { +crng_reseed ();/* Sets crng_init to CRNG_READY under base_crng.lock. */ +process_random_ready_list (); +wake_up_interruptible (&crng_init_wait); +kill_fasync (&fasync,SIGIO ,POLL_IN ); +pr_notice ("crng init done\n" ); +if (unseeded_warning.missed) { +pr_notice ("%d get_random_xx warning(s) missed due to ratelimiting\n" , + unseeded_warning.missed); + unseeded_warning.missed =0 ; + } +if (urandom_warning.missed) { +pr_notice ("%d urandom warning(s) missed due to ratelimiting\n" , + urandom_warning.missed); + urandom_warning.missed =0 ; + } + }else if (orig <POOL_EARLY_BITS && new >=POOL_EARLY_BITS ) {spin_lock_irqsave (&base_crng.lock, flags); +/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */ if (crng_init ==CRNG_EMPTY ) {extract_entropy (base_crng.key,sizeof (base_crng.key)); crng_init =CRNG_EARLY ;
Greg Kroah-Hartman
maintainerPATCH 202/264 random: remove ratelimiting for in-kernel unseeded randomness
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit cc1e127bfa95b5fb2f9307e7168bf8b2b45b4c5e upstream.
The CONFIG_WARN_ALL_UNSEEDED_RANDOM debug option controls whether the kernel warns about all unseeded randomness or just the first instance. There's some complicated rate limiting and comparison to the previous caller, such that even with CONFIG_WARN_ALL_UNSEEDED_RANDOM enabled, developers still don't see all the messages or even an accurate count of how many were missed. This is the result of basically parallel mechanisms aimed at accomplishing more or less the same thing, added at different points in random.c history, which sort of compete with the first-instance-only limiting we have now.
It turns out, however, that nobody cares about the first unseeded randomness instance of in-kernel users. The same first user has been there for ages now, and nobody is doing anything about it. It isn't even clear that anybody _can_ do anything about it. Most places that can do something about it have switched over to using get_random_bytes_wait() or wait_for_random_bytes(), which is the right thing to do, but there is still much code that needs randomness sometimes during init, and as a geeneral rule, if you're not using one of the _wait functions or the readiness notifier callback, you're bound to be doing it wrong just based on that fact alone.
So warning about this same first user that can't easily change is simply not an effective mechanism for anything at all. Users can't do anything about it, as the Kconfig text points out -- the problem isn't in userspace code -- and kernel developers don't or more often can't react to it.
Instead, show the warning for all instances when CONFIG_WARN_ALL_UNSEEDED_RANDOM is set, so that developers can debug things need be, or if it isn't set, don't show a warning at all.
At the same time, CONFIG_WARN_ALL_UNSEEDED_RANDOM now implies setting random.ratelimit_disable=1 on by default, since if you care about one you probably care about the other too. And we can clean up usage around the related urandom_warning ratelimiter as well (whose behavior isn't changing), so that it properly counts missed messages after the 10 message threshold is reached.
--- drivers/char/random.c | 61 ++++++++++++++------------------------------------ lib/Kconfig.debug | 5 +--- 2 files changed, 20 insertions(+), 46 deletions(-)
drivers/char/random.c +18 -43
@@ -87,11 +87,10 @@ static DEFINE_SPINLOCK(random_ready_chaistatic RAW_NOTIFIER_HEAD (random_ready_chain);/* Control how we warn userspace. */ -static struct ratelimit_state unseeded_warning = -RATELIMIT_STATE_INIT ("warn_unseeded_randomness" ,HZ ,3 );static struct ratelimit_state urandom_warning =RATELIMIT_STATE_INIT ("warn_urandom_randomness" ,HZ ,3 ); -static int ratelimit_disable__read_mostly ; +static int ratelimit_disable__read_mostly = +IS_ENABLED (CONFIG_WARN_ALL_UNSEEDED_RANDOM );module_param_named (ratelimit_disable, ratelimit_disable, int,0644 );MODULE_PARM_DESC (ratelimit_disable,"Disable random ratelimit suppression" );
@@ -184,27 +183,15 @@ static void process_random_ready_list(vospin_unlock_irqrestore (&random_ready_chain_lock, flags); } -#define warn_unseeded_randomness (previous) \ - _warn_unseeded_randomness(__func__, (void *)_RET_IP_, (previous)) +#define warn_unseeded_randomness () \ + _warn_unseeded_randomness(__func__, (void *)_RET_IP_) -static void _warn_unseeded_randomness (const char *func_name,void *caller,void **previous) +static void _warn_unseeded_randomness (const char *func_name,void *caller) { -#ifdef CONFIG_WARN_ALL_UNSEEDED_RANDOM -const bool print_once = false; -#else -static bool print_once__read_mostly ; -#endif - -if (print_once ||crng_ready () || - (previous && (caller ==READ_ONCE (*previous)))) +if (!IS_ENABLED (CONFIG_WARN_ALL_UNSEEDED_RANDOM ) ||crng_ready ())return ; -WRITE_ONCE (*previous, caller); -#ifndef CONFIG_WARN_ALL_UNSEEDED_RANDOM - print_once = true; -#endif -if (__ratelimit (&unseeded_warning)) -printk_deferred (KERN_NOTICE "random: %s called from %pS with crng_init=%d\n" , - func_name, caller, crng_init); +printk_deferred (KERN_NOTICE "random: %s called from %pS with crng_init=%d\n" , + func_name, caller, crng_init); }
@@ -455,9 +442,7 @@ static void _get_random_bytes(void *buf,*/ void get_random_bytes (void *buf,size_t nbytes) { -static void *previous; - -warn_unseeded_randomness (&previous); +warn_unseeded_randomness ();_get_random_bytes (buf, nbytes); }EXPORT_SYMBOL (get_random_bytes);
@@ -551,10 +536,9 @@ u64 get_random_u64(void)u64 ret;unsigned long flags;struct batched_entropy *batch; -static void *previous;unsigned long next_gen; -warn_unseeded_randomness (&previous); +warn_unseeded_randomness ();if (!crng_ready ()) {_get_random_bytes (&ret,sizeof (ret));
@@ -589,10 +573,9 @@ u32 get_random_u32(void)u32 ret;unsigned long flags;struct batched_entropy *batch; -static void *previous;unsigned long next_gen; -warn_unseeded_randomness (&previous); +warn_unseeded_randomness ();if (!crng_ready ()) {_get_random_bytes (&ret,sizeof (ret));
@@ -819,16 +802,9 @@ static void credit_init_bits(size_t nbitwake_up_interruptible (&crng_init_wait);kill_fasync (&fasync,SIGIO ,POLL_IN );pr_notice ("crng init done\n" ); -if (unseeded_warning.missed) { -pr_notice ("%d get_random_xx warning(s) missed due to ratelimiting\n" , - unseeded_warning.missed); - unseeded_warning.missed =0 ; - } -if (urandom_warning.missed) { +if (urandom_warning.missed)pr_notice ("%d urandom warning(s) missed due to ratelimiting\n" , urandom_warning.missed); - urandom_warning.missed =0 ; - } }else if (orig <POOL_EARLY_BITS && new >=POOL_EARLY_BITS ) {spin_lock_irqsave (&base_crng.lock, flags);/* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
@@ -941,10 +917,6 @@ int __init rand_initialize(void)else if (arch_init && trust_cpu)credit_init_bits (BLAKE2S_BLOCK_SIZE *8 ); -if (ratelimit_disable) { - urandom_warning.interval =0 ; - unseeded_warning.interval =0 ; - }return 0 ; }
@@ -1390,11 +1362,14 @@ static ssize_t urandom_read(struct file {static int maxwarn =10 ; -if (!crng_ready () && maxwarn >0 ) { - maxwarn--; -if (__ratelimit (&urandom_warning)) +if (!crng_ready ()) { +if (!ratelimit_disable && maxwarn <=0 ) + ++urandom_warning.missed; +else if (ratelimit_disable ||__ratelimit (&urandom_warning)) { + --maxwarn;pr_notice ("%s: uninitialized urandom read (%zd bytes read)\n" , current->comm, nbytes); + } }return get_random_bytes_user (buf, nbytes);
lib/Kconfig.debug +2 -3
@@ -1195,9 +1195,8 @@ config WARN_ALL_UNSEEDED_RANDOM time. This is really bad from a security perspective, and so architecture maintainers really need to do what they can to get the CRNG seeded sooner after the system is booted. - However, since users can not do anything actionble to - address this, by default the kernel will issue only a single - warning for the first use of unseeded randomness. + However, since users cannot do anything actionable to + address this, by default this option is disabled. Say Y here if you want to receive warnings for all uses of unseeded randomness. This will be of use primarily for
Greg Kroah-Hartman
maintainerPATCH 203/264 random: use proper jiffies comparison macro
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 8a5b8a4a4ceb353b4dd5bafd09e2b15751bcdb51 upstream.
This expands to exactly the same code that it replaces, but makes things consistent by using the same macro for jiffy comparisons throughout.
--- drivers/char/random.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/char/random.c +1 -1
@@ -325,7 +325,7 @@ static bool crng_has_old_seed(void) interval = max_t(unsigned int, CRNG_RESEED_START_INTERVAL, (unsigned int )uptime /2 *HZ ); } -return time_after (jiffies,READ_ONCE (base_crng.birth) + interval); +return time_is_before_jiffies (READ_ONCE (base_crng.birth) + interval); }/*
Greg Kroah-Hartman
maintainerPATCH 204/264 random: handle latent entropy and command line from random_init()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 2f14062bb14b0fcfcc21e6dc7d5b5c0d25966164 upstream.
Currently, start_kernel() adds latent entropy and the command line to the entropy bool *after* the RNG has been initialized, deferring when it's actually used by things like stack canaries until the next time the pool is seeded. This surely is not intended.
Rather than splitting up which entropy gets added where and when between start_kernel() and random_init(), just do everything in random_init(), which should eliminate these kinds of bugs in the future.
While we're at it, rename the awkwardly titled "rand_initialize()" to the more standard "random_init()" nomenclature.
--- drivers/char/random.c | 13 ++++++++----- include/linux/random.h | 16 +++++++--------- init/main.c | 10 +++------- 3 files changed, 18 insertions(+), 21 deletions(-)
drivers/char/random.c +8 -5
@@ -884,12 +884,13 @@ early_param("random.trust_bootloader", p/* * The first collection of entropy occurs at system boot while interrupts -* are still turned off. Here we push in RDSEED, a timestamp, and utsname(). -* Depending on the above configuration knob, RDSEED may be considered -* sufficient for initialization. Note that much earlier setup may already -* have pushed entropy into the input pool by the time we get here. +* are still turned off. Here we push in latent entropy, RDSEED, a timestamp, +* utsname(), and the command line. Depending on the above configuration knob, +* RDSEED may be considered sufficient for initialization. Note that much +* earlier setup may already have pushed entropy into the input pool by the +* time we get here. */ -int __init rand_initialize (void ) +int __init random_init (const char *command_line) {size_t i;ktime_t now =ktime_get_real ();
@@ -911,6 +912,8 @@ int __init rand_initialize(void) }_mix_pool_bytes (&now,sizeof (now));_mix_pool_bytes (utsname (),sizeof (*(utsname ()))); +_mix_pool_bytes (command_line,strlen (command_line)); +add_latent_entropy ();if (crng_ready ())crng_reseed ();
include/linux/random.h +7 -9
@@ -14,26 +14,24 @@ struct notifier_block;extern void add_device_randomness (const void *,size_t );extern void add_bootloader_randomness (const void *,size_t ); +extern void add_input_randomness(unsigned int type, unsigned int code, + unsigned int value) __latent_entropy; +extern void add_interrupt_randomness(int irq) __latent_entropy; +extern void add_hwgenerator_randomness (const void *buffer,size_t count, +size_t entropy);#if defined(LATENT_ENTROPY_PLUGIN ) && !defined(__CHECKER__)static inline void add_latent_entropy (void ) { -add_device_randomness ((const void *)&latent_entropy, -sizeof (latent_entropy)); +add_device_randomness ((const void *)&latent_entropy,sizeof (latent_entropy)); }#else static inline void add_latent_entropy (void ) {}#endif -extern void add_input_randomness(unsigned int type, unsigned int code, - unsigned int value) __latent_entropy; -extern void add_interrupt_randomness(int irq) __latent_entropy; -extern void add_hwgenerator_randomness (const void *buffer,size_t count, -size_t entropy); -extern void get_random_bytes (void *buf,size_t nbytes);extern int wait_for_random_bytes (void ); -extern int __init rand_initialize (void ); +extern int __init random_init (const char *command_line);extern bool rng_is_initialized (void );extern int register_random_ready_notifier (struct notifier_block *nb);extern int unregister_random_ready_notifier (struct notifier_block *nb);
init/main.c +3 -7
@@ -583,15 +583,11 @@ asmlinkage __visible void __init start_k/* * For best initial stack canary entropy, prepare it after: * - setup_arch() for any UEFI RNG entropy and boot cmdline access -* - timekeeping_init() for ktime entropy used in rand_initialize() +* - timekeeping_init() for ktime entropy used in random_init() * - time_init() for making random_get_entropy() work on some platforms -* - rand_initialize() to get any arch-specific entropy like RDRAND -* - add_latent_entropy() to get any latent entropy -* - adding command line entropy +* - random_init() to initialize the RNG from from early entropy sources */ -rand_initialize (); -add_latent_entropy (); -add_device_randomness (command_line,strlen (command_line)); +random_init (command_line);boot_init_stack_canary ();sched_clock_postinit ();
Greg Kroah-Hartman
maintainerPATCH 205/264 random: credit architectural init the exact amount
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 12e45a2a6308105469968951e6d563e8f4fea187 upstream.
RDRAND and RDSEED can fail sometimes, which is fine. We currently initialize the RNG with 512 bits of RDRAND/RDSEED. We only need 256 bits of those to succeed in order to initialize the RNG. Instead of the current "all or nothing" approach, actually credit these contributions the amount that is actually contributed.
--- drivers/char/random.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/char/random.c +6 -6
@@ -892,9 +892,8 @@ early_param("random.trust_bootloader", p*/ int __init random_init (const char *command_line) { -size_t i;ktime_t now =ktime_get_real (); -bool arch_init = true; +unsigned int i, arch_bytes;unsigned long rv;#if defined(LATENT_ENTROPY_PLUGIN )
@@ -902,11 +901,12 @@ int __init random_init(const char *comma_mix_pool_bytes (compiletime_seed,sizeof (compiletime_seed));#endif -for (i =0 ; i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) { +for (i =0 , arch_bytes =BLAKE2S_BLOCK_SIZE ; + i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) {if (!arch_get_random_seed_long_early (&rv) && !arch_get_random_long_early (&rv)) { rv =random_get_entropy (); - arch_init = false; + arch_bytes -=sizeof (rv); }_mix_pool_bytes (&rv,sizeof (rv)); }
@@ -917,8 +917,8 @@ int __init random_init(const char *commaif (crng_ready ())crng_reseed (); -else if (arch_init && trust_cpu) -credit_init_bits (BLAKE2S_BLOCK_SIZE *8 ); +else if (trust_cpu) +credit_init_bits (arch_bytes *8 );return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 206/264 random: use static branch for crng_ready()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit f5bda35fba615ace70a656d4700423fa6c9bebee upstream.
Since crng_ready() is only false briefly during initialization and then forever after becomes true, we don't need to evaluate it after, making it a prime candidate for a static branch.
One complication, however, is that it changes state in a particular call to credit_init_bits(), which might be made from atomic context, which means we must kick off a workqueue to change the static key. Further complicating things, credit_init_bits() may be called sufficiently early on in system initialization such that system_wq is NULL.
Fortunately, there exists the nice function execute_in_process_context(), which will immediately execute the function if !in_interrupt(), and otherwise defer it to a workqueue. During early init, before workqueues are available, in_interrupt() is always false, because interrupts haven't even been enabled yet, which means the function in that case executes immediately. Later on, after workqueues are available, in_interrupt() might be true, but in that case, the work is queued in system_wq and all goes well.
--- drivers/char/random.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
drivers/char/random.c +12 -4
@@ -78,8 +78,9 @@ 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 =CRNG_EMPTY ; -#define crng_ready () (likely(crng_init >= CRNG_READY)) +} 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;
@@ -109,6 +110,11 @@ bool rng_is_initialized(void) }EXPORT_SYMBOL (rng_is_initialized); +static void 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 );
@@ -268,7 +274,7 @@ static void crng_reseed(void) ++next_gen;WRITE_ONCE (base_crng.generation, next_gen);WRITE_ONCE (base_crng.birth, jiffies); -if (!crng_ready ()) +if (!static_branch_likely (&crng_is_ready)) crng_init =CRNG_READY ;spin_unlock_irqrestore (&base_crng.lock, flags);memzero_explicit (key,sizeof (key));
@@ -783,6 +789,7 @@ static void extract_entropy(void *buf, sstatic void credit_init_bits (size_t nbits) { +static struct execute_work set_ready;unsigned int new, orig, add;unsigned long flags;
@@ -798,6 +805,7 @@ static void credit_init_bits(size_t nbitif (orig <POOL_READY_BITS && new >=POOL_READY_BITS ) {crng_reseed ();/* Sets crng_init to CRNG_READY under base_crng.lock. */ +execute_in_process_context (crng_set_ready, &set_ready);process_random_ready_list ();wake_up_interruptible (&crng_init_wait);kill_fasync (&fasync,SIGIO ,POLL_IN );
@@ -1307,7 +1315,7 @@ SYSCALL_DEFINE3(getrandom, char __user *if (count >INT_MAX ) count =INT_MAX ; -if (!(flags &GRND_INSECURE ) && !crng_ready ()) { +if (!crng_ready () && !(flags &GRND_INSECURE )) {int ret;if (flags &GRND_NONBLOCK )
Greg Kroah-Hartman
maintainerPATCH 207/264 random: remove extern from functions in header
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 7782cfeca7d420e8bb707613d4cfb0f7ff29bb3a upstream.
Accoriding to the kernel style guide, having extern on functions in headers is old school and deprecated, and doesn't add anything. So remove them from random.h, and tidy up the file a little bit too.
--- include/linux/random.h | 67 +++++++++++++++++++------------------------------ 1 file changed, 27 insertions(+), 40 deletions(-)
include/linux/random.h +27 -40
@@ -12,13 +12,12 @@struct notifier_block ; -extern void add_device_randomness (const void *,size_t ); -extern void add_bootloader_randomness (const void *,size_t ); -extern void add_input_randomness(unsigned int type, unsigned int code, - unsigned int value) __latent_entropy; -extern void add_interrupt_randomness(int irq) __latent_entropy; -extern void add_hwgenerator_randomness (const void *buffer,size_t count, -size_t entropy); +void add_device_randomness (const void *,size_t ); +void add_bootloader_randomness (const void *,size_t ); +void add_input_randomness(unsigned int type, unsigned int code, + unsigned int value) __latent_entropy; +void add_interrupt_randomness(int irq) __latent_entropy; +void add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy);#if defined(LATENT_ENTROPY_PLUGIN ) && !defined(__CHECKER__)static inline void add_latent_entropy (void )
@@ -26,21 +25,11 @@ static inline void add_latent_entropy(vo add_device_randomness((const void *)&latent_entropy, sizeof(latent_entropy)); }#else -static inline void add_latent_entropy (void ) {} -#endif - -extern void get_random_bytes (void *buf,size_t nbytes); -extern int wait_for_random_bytes (void ); -extern int __init random_init (const char *command_line); -extern bool rng_is_initialized (void ); -extern int register_random_ready_notifier (struct notifier_block *nb); -extern int unregister_random_ready_notifier (struct notifier_block *nb); -extern size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes); - -#ifndef MODULE -extern const struct file_operations random_fops, urandom_fops; +static inline void add_latent_entropy (void ) { }#endif +void get_random_bytes (void *buf,size_t nbytes); +size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes);u32 get_random_u32 (void );u64 get_random_u64 (void );static inline unsigned int get_random_int (void )
@@ -56,6 +45,14 @@ static inline unsigned long get_random_l#endif } +unsigned long randomize_page (unsigned long start,unsigned long range); + +int __init random_init (const char *command_line); +bool rng_is_initialized (void ); +int wait_for_random_bytes (void ); +int register_random_ready_notifier (struct notifier_block *nb); +int unregister_random_ready_notifier (struct notifier_block *nb); +/* Calls wait_for_random_bytes() and then calls get_random_bytes(buf, nbytes). * Returns the result of the call to wait_for_random_bytes. */ static inline int get_random_bytes_wait (void *buf,size_t nbytes)
@@ -79,8 +76,6 @@ declare_get_random_var_wait(int)declare_get_random_var_wait (long ) #undef declare_get_random_var -unsigned long randomize_page (unsigned long start,unsigned long range); -/* * This is designed to be standalone for just prandom * users, but for now we include it from <linux/random.h>
@@ -91,22 +86,10 @@ unsigned long randomize_page(unsigned lo#ifdef CONFIG_ARCH_RANDOM # include <asm/archrandom.h> #else -static inline bool __must_check arch_get_random_long (unsigned long *v) -{ -return false; -} -static inline bool __must_check arch_get_random_int (unsigned int *v) -{ -return false; -} -static inline bool __must_check arch_get_random_seed_long (unsigned long *v) -{ -return false; -} -static inline bool __must_check arch_get_random_seed_int (unsigned int *v) -{ -return false; -} +static inline bool __must_check arch_get_random_long (unsigned long *v) {return false; } +static inline bool __must_check arch_get_random_int (unsigned int *v) {return false; } +static inline bool __must_check arch_get_random_seed_long (unsigned long *v) {return false; } +static inline bool __must_check arch_get_random_seed_int (unsigned int *v) {return false; }#endif /*
@@ -130,8 +113,12 @@ static inline bool __init arch_get_rando#endif #ifdef CONFIG_SMP -extern int random_prepare_cpu (unsigned int cpu); -extern int random_online_cpu (unsigned int cpu); +int random_prepare_cpu (unsigned int cpu); +int random_online_cpu (unsigned int cpu); +#endif + +#ifndef MODULE +extern const struct file_operations random_fops, urandom_fops;#endif #endif /* _LINUX_RANDOM_H */
Greg Kroah-Hartman
maintainerPATCH 208/264 random: use proper return types on get_random_{int,long}_wait()
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 7c3a8a1db5e03d02cc0abb3357a84b8b326dfac3 upstream.
Before these were returning signed values, but the API is intended to be used with unsigned values.
--- drivers/char/random.c | 195 +++++++++++++++++++++++-------------------------- include/linux/random.h | 24 +++--- 2 files changed, 107 insertions(+), 112 deletions(-)
drivers/char/random.c +95 -100
@@ -211,7 +211,7 @@ static void _warn_unseeded_randomness(co* * There are a few exported interfaces for use by other drivers: * -* void get_random_bytes(void *buf, size_t nbytes) +* void get_random_bytes(void *buf, size_t len) * u32 get_random_u32() * u64 get_random_u64() * unsigned int get_random_int()
@@ -250,7 +250,7 @@ static DEFINE_PER_CPU(struct crng, crngs };/* 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 nbytes); +static void extract_entropy (void *buf,size_t len);/* This extracts a new crng key from the input pool. */ static void crng_reseed (void )
@@ -404,24 +404,24 @@ static void crng_make_state(u32 chacha_slocal_irq_restore (flags); } -static void _get_random_bytes (void *buf,size_t nbytes) +static void _get_random_bytes (void *buf,size_t len) {u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)];u8 tmp[CHACHA20_BLOCK_SIZE ]; -size_t len; +size_t first_block_len; -if (!nbytes) +if (!len)return ; - len =min_t (size_t,32 , nbytes); -crng_make_state (chacha_state, buf, len); - nbytes -= len; - buf += len; + 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 (nbytes) { -if (nbytes <CHACHA20_BLOCK_SIZE ) { +while (len) { +if (len <CHACHA20_BLOCK_SIZE ) {chacha20_block (chacha_state, tmp); -memcpy (buf, tmp, nbytes); +memcpy (buf, tmp, len);memzero_explicit (tmp,sizeof (tmp));break ; }
@@ -429,7 +429,7 @@ static void _get_random_bytes(void *buf,chacha20_block (chacha_state, buf);if (unlikely (chacha_state[12 ] ==0 )) ++chacha_state[13 ]; - nbytes -=CHACHA20_BLOCK_SIZE ; + len -=CHACHA20_BLOCK_SIZE ; buf +=CHACHA20_BLOCK_SIZE ; }
@@ -446,20 +446,20 @@ static void _get_random_bytes(void *buf,* 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 nbytes) +void get_random_bytes (void *buf,size_t len) {warn_unseeded_randomness (); -_get_random_bytes (buf, nbytes); +_get_random_bytes (buf, len); }EXPORT_SYMBOL (get_random_bytes); -static ssize_t get_random_bytes_user (void __user *buf,size_t nbytes) +static ssize_t get_random_bytes_user (void __user *ubuf,size_t len) { -size_t len, left, ret =0 ; +size_t block_len, left, ret =0 ;u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)];u8 output[CHACHA20_BLOCK_SIZE ]; -if (!nbytes) +if (!len)return 0 ;/*
@@ -473,8 +473,8 @@ static ssize_t get_random_bytes_user(voi* use chacha_state after, so we can simply return those bytes to * the user directly. */ -if (nbytes <=CHACHA20_KEY_SIZE ) { - ret = nbytes -copy_to_user (buf, &chacha_state[4 ], nbytes); +if (len <=CHACHA20_KEY_SIZE ) { + ret = len -copy_to_user (ubuf, &chacha_state[4 ], len); goto out_zero_chacha; }
@@ -483,17 +483,17 @@ static ssize_t get_random_bytes_user(voiif (unlikely (chacha_state[12 ] ==0 )) ++chacha_state[13 ]; - len =min_t (size_t, nbytes,CHACHA20_BLOCK_SIZE ); - left =copy_to_user (buf, output, len); + block_len =min_t (size_t, len,CHACHA20_BLOCK_SIZE ); + left =copy_to_user (ubuf, output, block_len);if (left) { - ret += len - left; + ret += block_len - left;break ; } - buf += len; - ret += len; - nbytes -= len; -if (!nbytes) + ubuf += block_len; + ret += block_len; + len -= block_len; +if (!len)break ;BUILD_BUG_ON (PAGE_SIZE %CHACHA20_BLOCK_SIZE !=0 );
@@ -664,24 +664,24 @@ unsigned long randomize_page(unsigned lo* use. Use get_random_bytes() instead. It returns the number of * bytes filled in. */ -size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes) +size_t __must_check get_random_bytes_arch (void *buf,size_t len) { -size_t left = nbytes; +size_t left = len;u8 *p = buf;while (left) {unsigned long v; -size_t chunk =min_t (size_t, left,sizeof (unsigned long )); +size_t block_len =min_t (size_t, left,sizeof (unsigned long ));if (!arch_get_random_long (&v))break ; -memcpy (p, &v, chunk); - p += chunk; - left -= chunk; +memcpy (p, &v, block_len); + p += block_len; + left -= block_len; } -return nbytes - left; +return len - left; }EXPORT_SYMBOL (get_random_bytes_arch);
@@ -692,15 +692,15 @@ EXPORT_SYMBOL(get_random_bytes_arch);* * Callers may add entropy via: * -* static void mix_pool_bytes(const void *in, size_t nbytes) +* static void mix_pool_bytes(const void *buf, size_t len) * * After which, if added entropy should be credited: * -* static void credit_init_bits(size_t nbits) +* static void credit_init_bits(size_t bits) * * Finally, extract entropy via: * -* static void extract_entropy(void *buf, size_t nbytes) +* static void extract_entropy(void *buf, size_t len) * **********************************************************************/
@@ -722,9 +722,9 @@ static struct { .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock), }; -static void _mix_pool_bytes (const void *in,size_t nbytes) +static void _mix_pool_bytes (const void *buf,size_t len) { -blake2s_update (&input_pool.hash, in, nbytes); +blake2s_update (&input_pool.hash, buf, len); }/*
@@ -732,12 +732,12 @@ static void _mix_pool_bytes(const void ** update the initialization bit counter; the caller should call * credit_init_bits if this is appropriate. */ -static void mix_pool_bytes (const void *in,size_t nbytes) +static void mix_pool_bytes (const void *buf,size_t len) {unsigned long flags;spin_lock_irqsave (&input_pool.lock, flags); -_mix_pool_bytes (in, nbytes); +_mix_pool_bytes (buf, len);spin_unlock_irqrestore (&input_pool.lock, flags); }
@@ -745,7 +745,7 @@ static void mix_pool_bytes(const void *i* This is an HKDF-like construction for using the hashed collected entropy * as a PRF key, that's then expanded block-by-block. */ -static void extract_entropy (void *buf,size_t nbytes) +static void extract_entropy (void *buf,size_t len) {unsigned long flags;u8 seed[BLAKE2S_HASH_SIZE ], next_key[BLAKE2S_HASH_SIZE ];
@@ -774,12 +774,12 @@ static void extract_entropy(void *buf, sspin_unlock_irqrestore (&input_pool.lock, flags);memzero_explicit (next_key,sizeof (next_key)); -while (nbytes) { - i =min_t (size_t, nbytes,BLAKE2S_HASH_SIZE ); +while (len) { + i =min_t (size_t, len,BLAKE2S_HASH_SIZE );/* output = HASHPRF(seed, RDSEED || ++counter) */ ++block.counter;blake2s (buf, (u8 *)&block, seed, i,sizeof (block),sizeof (seed)); - nbytes -= i; + len -= i; buf += i; }
@@ -787,16 +787,16 @@ static void extract_entropy(void *buf, smemzero_explicit (&block,sizeof (block)); } -static void credit_init_bits (size_t nbits) +static void credit_init_bits (size_t bits) {static struct execute_work set_ready;unsigned int new, orig, add;unsigned long flags; -if (crng_ready () || !nbits) +if (crng_ready () || !bits)return ; - add =min_t (size_t, nbits,POOL_BITS ); + add =min_t (size_t, bits,POOL_BITS ); do { orig = READ_ONCE(input_pool.init_bits);
@@ -832,13 +832,11 @@ static void credit_init_bits(size_t nbit* The following exported functions are used for pushing entropy into * the above entropy accumulation routines: * -* void add_device_randomness(const void *buf, size_t size); -* void add_hwgenerator_randomness(const void *buffer, size_t count, -* size_t entropy); -* void add_bootloader_randomness(const void *buf, size_t size); +* void add_device_randomness(const void *buf, size_t len); +* void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy); +* void add_bootloader_randomness(const void *buf, size_t len); * void add_interrupt_randomness(int irq); -* void add_input_randomness(unsigned int type, unsigned int code, -* unsigned int value); +* void add_input_randomness(unsigned int type, unsigned int code, unsigned int value); * void add_disk_randomness(struct gendisk *disk); * * add_device_randomness() adds data to the input pool that
@@ -902,7 +900,7 @@ int __init random_init(const char *comma {ktime_t now =ktime_get_real ();unsigned int i, arch_bytes; -unsigned long rv; +unsigned long entropy;#if defined(LATENT_ENTROPY_PLUGIN ) static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
@@ -910,13 +908,13 @@ int __init random_init(const char *comma#endif for (i =0 , arch_bytes =BLAKE2S_BLOCK_SIZE ; - i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (rv)) { -if (!arch_get_random_seed_long_early (&rv) && - !arch_get_random_long_early (&rv)) { - rv =random_get_entropy (); - arch_bytes -=sizeof (rv); + i <BLAKE2S_BLOCK_SIZE ; i +=sizeof (entropy)) { +if (!arch_get_random_seed_long_early (&entropy) && + !arch_get_random_long_early (&entropy)) { + entropy =random_get_entropy (); + arch_bytes -=sizeof (entropy); } -_mix_pool_bytes (&rv,sizeof (rv)); +_mix_pool_bytes (&entropy,sizeof (entropy)); }_mix_pool_bytes (&now,sizeof (now));_mix_pool_bytes (utsname (),sizeof (*(utsname ())));
@@ -939,14 +937,14 @@ int __init random_init(const char *comma* the entropy pool having similar initial state across largely * identical devices. */ -void add_device_randomness (const void *buf,size_t size) +void add_device_randomness (const void *buf,size_t len) {unsigned long entropy =random_get_entropy ();unsigned long flags;spin_lock_irqsave (&input_pool.lock, flags);_mix_pool_bytes (&entropy,sizeof (entropy)); -_mix_pool_bytes (buf, size); +_mix_pool_bytes (buf, len);spin_unlock_irqrestore (&input_pool.lock, flags); }EXPORT_SYMBOL (add_device_randomness);
@@ -956,10 +954,9 @@ EXPORT_SYMBOL(add_device_randomness);* Those devices may produce endless random bits and will be throttled * when our pool is full. */ -void add_hwgenerator_randomness (const void *buffer,size_t count, -size_t entropy) +void add_hwgenerator_randomness (const void *buf,size_t len,size_t entropy) { -mix_pool_bytes (buffer, count); +mix_pool_bytes (buf, len);credit_init_bits (entropy);/*
@@ -975,11 +972,11 @@ EXPORT_SYMBOL_GPL(add_hwgenerator_random* Handle random seed passed by bootloader, and credit it if * CONFIG_RANDOM_TRUST_BOOTLOADER is set. */ -void add_bootloader_randomness (const void *buf,size_t size) +void add_bootloader_randomness (const void *buf,size_t len) { -mix_pool_bytes (buf, size); +mix_pool_bytes (buf, len);if (trust_bootloader) -credit_init_bits (size *8 ); +credit_init_bits (len *8 ); }EXPORT_SYMBOL_GPL (add_bootloader_randomness);
@@ -1179,8 +1176,7 @@ static void add_timer_randomness(structcredit_init_bits (bits); } -void add_input_randomness (unsigned int type,unsigned int code, -unsigned int value) +void add_input_randomness (unsigned int type,unsigned int code,unsigned int value) {static unsigned char last_value;static struct timer_rand_state input_timer_state = {INITIAL_JIFFIES };
@@ -1299,8 +1295,7 @@ static void try_to_generate_entropy(void* **********************************************************************/ -SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count, unsigned int, - flags) +SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags) {if (flags & ~(GRND_NONBLOCK |GRND_RANDOM |GRND_INSECURE ))return -EINVAL ;
@@ -1312,8 +1307,8 @@ SYSCALL_DEFINE3(getrandom, char __user *if ((flags & (GRND_INSECURE |GRND_RANDOM )) == (GRND_INSECURE |GRND_RANDOM ))return -EINVAL ; -if (count >INT_MAX ) - count =INT_MAX ; +if (len >INT_MAX ) + len =INT_MAX ;if (!crng_ready () && !(flags &GRND_INSECURE )) {int ret;
@@ -1324,7 +1319,7 @@ SYSCALL_DEFINE3(getrandom, char __user *if (unlikely (ret))return ret; } -return get_random_bytes_user (buf, count); +return get_random_bytes_user (ubuf, len); }static unsigned int random_poll (struct file *file,poll_table *wait)
@@ -1333,21 +1328,21 @@ static unsigned int random_poll(struct freturn crng_ready () ?POLLIN |POLLRDNORM :POLLOUT |POLLWRNORM ; } -static int write_pool (const char __user *ubuf,size_t count) +static int write_pool (const char __user *ubuf,size_t len) { -size_t len; +size_t block_len;int ret =0 ;u8 block[BLAKE2S_BLOCK_SIZE ]; -while (count) { - len =min (count,sizeof (block)); -if (copy_from_user (block, ubuf, len)) { +while (len) { + block_len =min (len,sizeof (block)); +if (copy_from_user (block, ubuf, block_len)) { ret = -EFAULT ; goto out; } - count -= len; - ubuf += len; -mix_pool_bytes (block, len); + len -= block_len; + ubuf += block_len; +mix_pool_bytes (block, block_len);cond_resched (); }
@@ -1356,20 +1351,20 @@ out:return ret; } -static ssize_t random_write (struct file *file,const char __user *buffer, -size_t count,loff_t *ppos) +static ssize_t random_write (struct file *file,const char __user *ubuf, +size_t len,loff_t *ppos) {int ret; - ret =write_pool (buffer, count); + ret =write_pool (ubuf, len);if (ret)return ret; -return (ssize_t )count; +return (ssize_t )len; } -static ssize_t urandom_read (struct file *file,char __user *buf,size_t nbytes, -loff_t *ppos) +static ssize_t urandom_read (struct file *file,char __user *ubuf, +size_t len,loff_t *ppos) {static int maxwarn =10 ;
@@ -1379,22 +1374,22 @@ static ssize_t urandom_read(struct fileelse if (ratelimit_disable ||__ratelimit (&urandom_warning)) { --maxwarn;pr_notice ("%s: uninitialized urandom read (%zd bytes read)\n" , - current->comm, nbytes); + current->comm, len); } } -return get_random_bytes_user (buf, nbytes); +return get_random_bytes_user (ubuf, len); } -static ssize_t random_read (struct file *file,char __user *buf,size_t nbytes, -loff_t *ppos) +static ssize_t random_read (struct file *file,char __user *ubuf, +size_t len,loff_t *ppos) {int ret; ret =wait_for_random_bytes ();if (ret !=0 )return ret; -return get_random_bytes_user (buf, nbytes); +return get_random_bytes_user (ubuf, len); }static long random_ioctl (struct file *f,unsigned int cmd,unsigned long arg)
@@ -1517,8 +1512,8 @@ static u8 sysctl_bootid[UUID_SIZE];* UUID. The difference is in whether table->data is NULL; if it is, * then a new UUID is generated and returned to the user. */ -static int proc_do_uuid (struct ctl_table *table,int write, -void __user *buffer,size_t *lenp,loff_t *ppos) +static int proc_do_uuid (struct ctl_table *table,int write,void __user *buf, +size_t *lenp,loff_t *ppos) {u8 tmp_uuid[UUID_SIZE ], *uuid;char uuid_string[UUID_STRING_LEN +1 ];
@@ -1544,14 +1539,14 @@ static int proc_do_uuid(struct ctl_table }snprintf (uuid_string,sizeof (uuid_string),"%pU" , uuid); -return proc_dostring (&fake_table,0 , buffer, lenp, ppos); +return proc_dostring (&fake_table,0 , buf, lenp, ppos); }/* The same as proc_dointvec, but writes don't change anything. */ -static int proc_do_rointvec (struct ctl_table *table,int write,void __user *buffer, +static int proc_do_rointvec (struct ctl_table *table,int write,void __user *buf,size_t *lenp,loff_t *ppos) { -return write ?0 :proc_dointvec (table,0 , buffer, lenp, ppos); +return write ?0 :proc_dointvec (table,0 , buf, lenp, ppos); }extern struct ctl_table random_table[];
include/linux/random.h +12 -12
@@ -12,12 +12,12 @@struct notifier_block ; -void add_device_randomness (const void *,size_t ); -void add_bootloader_randomness (const void *,size_t ); +void add_device_randomness (const void *buf,size_t len); +void add_bootloader_randomness (const void *buf,size_t len); void add_input_randomness(unsigned int type, unsigned int code, unsigned int value) __latent_entropy; void add_interrupt_randomness(int irq) __latent_entropy; -void add_hwgenerator_randomness (const void *buffer,size_t count,size_t entropy); +void add_hwgenerator_randomness (const void *buf,size_t len,size_t entropy);#if defined(LATENT_ENTROPY_PLUGIN ) && !defined(__CHECKER__)static inline void add_latent_entropy (void )
@@ -28,8 +28,8 @@ static inline void add_latent_entropy(vostatic inline void add_latent_entropy (void ) { }#endif -void get_random_bytes (void *buf,size_t nbytes); -size_t __must_check get_random_bytes_arch (void *buf,size_t nbytes); +void get_random_bytes (void *buf,size_t len); +size_t __must_check get_random_bytes_arch (void *buf,size_t len);u32 get_random_u32 (void );u64 get_random_u64 (void );static inline unsigned int get_random_int (void )
@@ -62,18 +62,18 @@ static inline int get_random_bytes_wait(return ret; } -#define declare_get_random_var_wait (var) \ - static inline int get_random_ ## var ## _wait(var *out) { \ +#define declare_get_random_var_wait (name, ret_type) \ + static inline int get_random_ ## name ## _wait(ret_type *out) { \ int ret = wait_for_random_bytes(); \ if (unlikely(ret)) \ return ret; \ - *out = get_random_ ## var(); \ + *out = get_random_ ## name(); \ return 0; \ } -declare_get_random_var_wait(u32) -declare_get_random_var_wait(u64) -declare_get_random_var_wait(int) -declare_get_random_var_wait(long) +declare_get_random_var_wait(u32, u32) +declare_get_random_var_wait(u64, u32) +declare_get_random_var_wait(int, unsigned int) +declare_get_random_var_wait(long, unsigned long)#undef declare_get_random_var/*
Greg Kroah-Hartman
maintainerPATCH 209/264 random: move initialization functions out of hot pages
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 560181c27b582557d633ecb608110075433383af upstream.
Much of random.c is devoted to initializing the rng and accounting for when a sufficient amount of entropy has been added. In a perfect world, this would all happen during init, and so we could mark these functions as __init. But in reality, this isn't the case: sometimes the rng only finishes initializing some seconds after system init is finished.
For this reason, at the moment, a whole host of functions that are only used relatively close to system init and then never again are intermixed with functions that are used in hot code all the time. This creates more cache misses than necessary.
In order to pack the hot code closer together, this commit moves the initialization functions that can't be marked as __init into .text.unlikely by way of the __cold attribute.
Of particular note is moving credit_init_bits() into a macro wrapper that inlines the crng_ready() static branch check. This avoids a function call to a nop+ret, and most notably prevents extra entropy arithmetic from being computed in mix_interrupt_randomness().
[ Jason: for stable, made sure the printk_deferred was a pr_notice,
because those caused problems on ≤ 4.19 according to commit logs. ]
--- drivers/char/random.c | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-)
drivers/char/random.c +18 -22
@@ -110,7 +110,7 @@ bool rng_is_initialized(void) }EXPORT_SYMBOL (rng_is_initialized); -static void crng_set_ready (struct work_struct *work) +static void __cold crng_set_ready (struct work_struct *work) {static_branch_enable (&crng_is_ready); }
@@ -149,7 +149,7 @@ EXPORT_SYMBOL(wait_for_random_bytes);* returns: 0 if callback is successfully added * -EALREADY if pool is already initialised (callback not called) */ -int register_random_ready_notifier (struct notifier_block *nb) +int __cold register_random_ready_notifier (struct notifier_block *nb) {unsigned long flags;int ret = -EALREADY ;
@@ -168,7 +168,7 @@ EXPORT_SYMBOL(register_random_ready_noti/* * Delete a previously registered readiness callback function. */ -int unregister_random_ready_notifier (struct notifier_block *nb) +int __cold unregister_random_ready_notifier (struct notifier_block *nb) {unsigned long flags;int ret;
@@ -180,7 +180,7 @@ int unregister_random_ready_notifier(str }EXPORT_SYMBOL (unregister_random_ready_notifier); -static void process_random_ready_list (void ) +static void __cold process_random_ready_list (void ) {unsigned long flags;
@@ -190,15 +190,9 @@ static void process_random_ready_list(vo }#define warn_unseeded_randomness () \ - _warn_unseeded_randomness(__func__, (void *)_RET_IP_) - -static void _warn_unseeded_randomness (const char *func_name,void *caller) -{ -if (!IS_ENABLED (CONFIG_WARN_ALL_UNSEEDED_RANDOM ) ||crng_ready ()) -return ; -printk_deferred (KERN_NOTICE "random: %s called from %pS with crng_init=%d\n" , - func_name, caller, crng_init); -} + if (IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) && !crng_ready()) \ + pr_notice("%s called from %pS with crng_init=%d\n", \ + __func__, (void *)_RET_IP_, crng_init)/*********************************************************************
@@ -612,7 +606,7 @@ EXPORT_SYMBOL(get_random_u32);* This function is called when the CPU is coming up, with entry * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP. */ -int random_prepare_cpu (unsigned int cpu) +int __cold random_prepare_cpu (unsigned int cpu) {/* * When the cpu comes back online, immediately invalidate both
@@ -787,13 +781,15 @@ static void extract_entropy(void *buf, smemzero_explicit (&block,sizeof (block)); } -static void credit_init_bits (size_t bits) +#define credit_init_bits (bits) if (!crng_ready()) _credit_init_bits(bits) + +static void __cold _credit_init_bits (size_t bits) {static struct execute_work set_ready;unsigned int new, orig, add;unsigned long flags; -if (crng_ready () || !bits) +if (!bits)return ; add =min_t (size_t, bits,POOL_BITS );
@@ -972,7 +968,7 @@ EXPORT_SYMBOL_GPL(add_hwgenerator_random* Handle random seed passed by bootloader, and credit it if * CONFIG_RANDOM_TRUST_BOOTLOADER is set. */ -void add_bootloader_randomness (const void *buf,size_t len) +void __cold add_bootloader_randomness (const void *buf,size_t len) {mix_pool_bytes (buf, len);if (trust_bootloader)
@@ -1018,7 +1014,7 @@ static void fast_mix(unsigned long s[4],* This function is called when the CPU has just come online, with * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE. */ -int random_online_cpu (unsigned int cpu) +int __cold random_online_cpu (unsigned int cpu) {/* * During CPU shutdown and before CPU onlining, add_interrupt_
@@ -1173,7 +1169,7 @@ static void add_timer_randomness(structif (in_irq ())this_cpu_ptr (&irq_randomness)->count +=max (1u , bits *64 ) -1 ;else -credit_init_bits (bits); +_credit_init_bits (bits); }void add_input_randomness (unsigned int type,unsigned int code,unsigned int value)
@@ -1201,7 +1197,7 @@ void add_disk_randomness(struct gendisk }EXPORT_SYMBOL_GPL (add_disk_randomness); -void rand_initialize_disk (struct gendisk *disk) +void __cold rand_initialize_disk (struct gendisk *disk) {struct timer_rand_state *state;
@@ -1230,7 +1226,7 @@ void rand_initialize_disk(struct gendisk* * So the re-arming always happens in the entropy loop itself. */ -static void entropy_timer (unsigned long data) +static void __cold entropy_timer (unsigned long data) {credit_init_bits (1 ); }
@@ -1239,7 +1235,7 @@ static void entropy_timer(unsigned long* If we have an actual cycle counter, see if we can * generate enough entropy with timing noise */ -static void try_to_generate_entropy (void ) +static void __cold try_to_generate_entropy (void ) {struct {unsigned long entropy;
Greg Kroah-Hartman
maintainerPATCH 210/264 random: move randomize_page() into mm where it belongs
In reply to Greg Kroah-HartmanFrom: "Jason A. Donenfeld" <[email protected]>
commit 5ad7dd882e45d7fe432c32e896e2aaa0b21746ea upstream.
randomize_page is an mm function. It is documented like one. It contains the history of one. It has the naming convention of one. It looks just like another very similar function in mm, randomize_stack_top(). And it has always been maintained and updated by mm people. There is no need for it to be in random.c. In the "which shape does not look like the other ones" test, pointing to randomize_page() is correct.
So move randomize_page() into mm/util.c, right next to the similar randomize_stack_top() function.
This commit contains no actual code changes.
--- drivers/char/random.c | 238 ++++++++++++++++--------------------------------- include/linux/mm.h | 2 include/linux/random.h | 2 mm/util.c | 33 ++++++ 4 files changed, 117 insertions(+), 158 deletions(-)
drivers/char/random.c +82 -156
@@ -52,6 +52,7 @@#include <linux/completion.h> #include <linux/uuid.h> #include <linux/siphash.h> +#include <linux/uio.h> #include <crypto/chacha20.h> #include <crypto/blake2s.h> #include <asm/processor.h>
@@ -447,13 +448,13 @@ void get_random_bytes(void *buf, size_t }EXPORT_SYMBOL (get_random_bytes); -static ssize_t get_random_bytes_user (void __user *ubuf,size_t len) +static ssize_t get_random_bytes_user (struct iov_iter *iter) { -size_t block_len, left, ret =0 ;u32 chacha_state[CHACHA20_BLOCK_SIZE /sizeof (u32)]; -u8 output[CHACHA20_BLOCK_SIZE ]; +u8 block[CHACHA20_BLOCK_SIZE ]; +size_t ret =0 , copied; -if (!len) +if (unlikely (!iov_iter_count (iter)))return 0 ;/*
@@ -467,30 +468,22 @@ static ssize_t get_random_bytes_user(voi* use chacha_state after, so we can simply return those bytes to * the user directly. */ -if (len <=CHACHA20_KEY_SIZE ) { - ret = len -copy_to_user (ubuf, &chacha_state[4 ], len); +if (iov_iter_count (iter) <=CHACHA20_KEY_SIZE ) { + ret =copy_to_iter (&chacha_state[4 ],CHACHA20_KEY_SIZE , iter); goto out_zero_chacha; }for (;;) { -chacha20_block (chacha_state, output); +chacha20_block (chacha_state, block);if (unlikely (chacha_state[12 ] ==0 )) ++chacha_state[13 ]; - block_len =min_t (size_t, len,CHACHA20_BLOCK_SIZE ); - left =copy_to_user (ubuf, output, block_len); -if (left) { - ret += block_len - left; + copied =copy_to_iter (block,sizeof (block), iter); + ret += copied; +if (!iov_iter_count (iter) || copied !=sizeof (block))break ; - } - ubuf += block_len; - ret += block_len; - len -= block_len; -if (!len) -break ; - -BUILD_BUG_ON (PAGE_SIZE %CHACHA20_BLOCK_SIZE !=0 ); +BUILD_BUG_ON (PAGE_SIZE %sizeof (block) !=0 );if (ret %PAGE_SIZE ==0 ) {if (signal_pending (current))break ;
@@ -498,7 +491,7 @@ static ssize_t get_random_bytes_user(voi } } -memzero_explicit (output,sizeof (output)); +memzero_explicit (block,sizeof (block)); out_zero_chacha:memzero_explicit (chacha_state,sizeof (chacha_state));return ret ? ret : -EFAULT ;
@@ -510,96 +503,60 @@ out_zero_chacha:* 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. */ -struct batched_entropy { -union { -/* -* 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) * CHACHA20_BLOCK_SIZE. -*/ -u64 entropy_u64[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u64))]; -u32 entropy_u32[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (u32))]; - }; -unsigned long generation; -unsigned int position; -}; - - -static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u64) = { - .position =UINT_MAX -}; - -u64 get_random_u64 (void ) -{ -u64 ret; -unsigned long flags; -struct batched_entropy *batch; -unsigned long next_gen; - -warn_unseeded_randomness (); - -if (!crng_ready ()) { -_get_random_bytes (&ret,sizeof (ret)); -return ret; - } - -local_irq_save (flags); - batch =raw_cpu_ptr (&batched_entropy_u64); - - next_gen =READ_ONCE (base_crng.generation); -if (batch->position >=ARRAY_SIZE (batch->entropy_u64) || - next_gen != batch->generation) { -_get_random_bytes (batch->entropy_u64,sizeof (batch->entropy_u64)); - batch->position =0 ; - batch->generation = next_gen; - } - - ret = batch->entropy_u64[batch->position]; - batch->entropy_u64[batch->position] =0 ; - ++batch->position; -local_irq_restore (flags); -return ret; -} -EXPORT_SYMBOL (get_random_u64); - -static DEFINE_PER_CPU(struct batched_entropy, batched_entropy_u32) = { - .position =UINT_MAX -}; - -u32 get_random_u32 (void ) -{ -u32 ret; -unsigned long flags; -struct batched_entropy *batch; -unsigned long next_gen; -warn_unseeded_randomness (); +#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) * CHACHA20_BLOCK_SIZE. \ +*/ \ +type entropy[CHACHA20_BLOCK_SIZE *3 / (2 *sizeof (type))]; \ +unsigned long generation; \ +unsigned int position; \ +}; \ + \ +static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = { \ + .position = UINT_MAX \ +}; \ + \ +type get_random_ ##type(void) \ +{ \ + type ret; \ + unsigned long flags; \ + struct batch_ ##type *batch; \ + unsigned long next_gen; \ + \ + warn_unseeded_randomness(); \ + \ + if (!crng_ready()) { \ + _get_random_bytes(&ret, sizeof(ret)); \ + return ret; \ + } \ + \ + local_irq_save(flags); \ + batch = raw_cpu_ptr(&batched_entropy_##type); \ + \ + next_gen = READ_ONCE(base_crng.generation); \ + if (batch->position >= ARRAY_SIZE(batch->entropy) || \ + next_gen != batch->generation) { \ + _get_random_bytes(batch->entropy, sizeof(batch->entropy)); \ + batch->position = 0; \ + batch->generation = next_gen; \ + } \ + \ + ret = batch->entropy[batch->position]; \ + batch->entropy[batch->position] = 0; \ + ++batch->position; \ + local_irq_restore(flags); \ + return ret; \ +} \ +EXPORT_SYMBOL(get_random_ ##type); -if (!crng_ready ()) { -_get_random_bytes (&ret,sizeof (ret)); -return ret; - } - -local_irq_save (flags); - batch =raw_cpu_ptr (&batched_entropy_u32); - - next_gen =READ_ONCE (base_crng.generation); -if (batch->position >=ARRAY_SIZE (batch->entropy_u32) || - next_gen != batch->generation) { -_get_random_bytes (batch->entropy_u32,sizeof (batch->entropy_u32)); - batch->position =0 ; - batch->generation = next_gen; - } - - ret = batch->entropy_u32[batch->position]; - batch->entropy_u32[batch->position] =0 ; - ++batch->position; -local_irq_restore (flags); -return ret; -} -EXPORT_SYMBOL (get_random_u32); +DEFINE_BATCHED_ENTROPY(u64) +DEFINE_BATCHED_ENTROPY(u32)#ifdef CONFIG_SMP /*
@@ -620,38 +577,6 @@ int __cold random_prepare_cpu(unsigned i }#endif -/** -* randomize_page - Generate a random, page aligned address -* @start: The smallest acceptable address the caller will take. -* @range: The size of the area, starting at @start, within which the -* random address must fall. -* -* If @start + @range would overflow, @range is capped. -* -* NOTE: Historical use of randomize_range, which this replaces, presumed that -* @start was already page aligned. We now align it regardless. -* -* Return: A page aligned address within [start, start + range). On error, -* @start is returned. -*/ -unsigned long randomize_page (unsigned long start,unsigned long range) -{ -if (!PAGE_ALIGNED (start)) { - range -=PAGE_ALIGN (start) - start; - start =PAGE_ALIGN (start); - } - -if (start >ULONG_MAX - range) - range =ULONG_MAX - start; - - range >>=PAGE_SHIFT ; - -if (range ==0 ) -return start; - -return start + (get_random_long () % range <<PAGE_SHIFT ); -} -/* * This function will use the architecture-specific hardware random * number generator if it is available. It is not recommended for
@@ -1293,6 +1218,10 @@ static void __cold try_to_generate_entro SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags) { +struct iov_iter iter; +struct iovec iov; +int ret; +if (flags & ~(GRND_NONBLOCK |GRND_RANDOM |GRND_INSECURE ))return -EINVAL ;
@@ -1303,19 +1232,18 @@ SYSCALL_DEFINE3(getrandom, char __user *if ((flags & (GRND_INSECURE |GRND_RANDOM )) == (GRND_INSECURE |GRND_RANDOM ))return -EINVAL ; -if (len >INT_MAX ) - len =INT_MAX ; -if (!crng_ready () && !(flags &GRND_INSECURE )) { -int ret; -if (flags &GRND_NONBLOCK )return -EAGAIN ; ret =wait_for_random_bytes ();if (unlikely (ret))return ret; } -return get_random_bytes_user (ubuf, len); + + ret =import_single_range (READ , ubuf, len, &iov, &iter); +if (unlikely (ret)) +return ret; +return get_random_bytes_user (&iter); }static unsigned int random_poll (struct file *file,poll_table *wait)
@@ -1359,8 +1287,7 @@ static ssize_t random_write(struct filereturn (ssize_t )len; } -static ssize_t urandom_read (struct file *file,char __user *ubuf, -size_t len,loff_t *ppos) +static ssize_t urandom_read_iter (struct kiocb *kiocb,struct iov_iter *iter) {static int maxwarn =10 ;
@@ -1369,23 +1296,22 @@ static ssize_t urandom_read(struct file ++urandom_warning.missed; else if (ratelimit_disable || __ratelimit(&urandom_warning)) { --maxwarn; -pr_notice ("%s: uninitialized urandom read (%zd bytes read)\n" , - current->comm, len); +pr_notice ("%s: uninitialized urandom read (%zu bytes read)\n" , + current->comm,iov_iter_count (iter)); } } -return get_random_bytes_user (ubuf, len); +return get_random_bytes_user (iter); } -static ssize_t random_read (struct file *file,char __user *ubuf, -size_t len,loff_t *ppos) +static ssize_t random_read_iter (struct kiocb *kiocb,struct iov_iter *iter) {int ret; ret =wait_for_random_bytes ();if (ret !=0 )return ret; -return get_random_bytes_user (ubuf, len); +return get_random_bytes_user (iter); }static long random_ioctl (struct file *f,unsigned int cmd,unsigned long arg)
@@ -1447,7 +1373,7 @@ static int random_fasync(int fd, struct }const struct file_operations random_fops = { - .read = random_read, + .read_iter = random_read_iter, .write = random_write, .poll = random_poll, .unlocked_ioctl = random_ioctl,
@@ -1456,7 +1382,7 @@ const struct file_operations random_fops };const struct file_operations urandom_fops = { - .read = urandom_read, + .read_iter = urandom_read_iter, .write = random_write, .unlocked_ioctl = random_ioctl, .fasync = random_fasync,
include/linux/mm.h +2 -0
@@ -2059,6 +2059,8 @@ extern int install_special_mapping(struc unsigned long addr, unsigned long len, unsigned long flags, struct page **pages); +unsigned long randomize_page (unsigned long start,unsigned long range); +extern unsigned long get_unmapped_area (struct file *,unsigned long ,unsigned long ,unsigned long ,unsigned long ); extern unsigned long mmap_region(struct file *file, unsigned long addr,
include/linux/random.h +0 -2
@@ -45,8 +45,6 @@ static inline unsigned long get_random_l#endif } -unsigned long randomize_page (unsigned long start,unsigned long range); -int __init random_init (const char *command_line);bool rng_is_initialized (void );int wait_for_random_bytes (void );
mm/util.c +33 -0
@@ -11,6 +11,7 @@#include <linux/mman.h> #include <linux/hugetlb.h> #include <linux/vmalloc.h> +#include <linux/random.h> #include <asm/sections.h> #include <asm/uaccess.h>
@@ -261,6 +262,38 @@ int vma_is_stack_for_current(struct vm_areturn (vma->vm_start <=KSTK_ESP (t) && vma->vm_end >=KSTK_ESP (t)); } +/** +* randomize_page - Generate a random, page aligned address +* @start: The smallest acceptable address the caller will take. +* @range: The size of the area, starting at @start, within which the +* random address must fall. +* +* If @start + @range would overflow, @range is capped. +* +* NOTE: Historical use of randomize_range, which this replaces, presumed that +* @start was already page aligned. We now align it regardless. +* +* Return: A page aligned address within [start, start + range). On error, +* @start is returned. +*/ +unsigned long randomize_page (unsigned long start,unsigned long range) +{ +if (!PAGE_ALIGNED (start)) { + range -=PAGE_ALIGN (start) - start; + start =PAGE_ALIGN (start); + } + +if (start >ULONG_MAX - range) + range =ULONG_MAX - start; + + range >>=PAGE_SHIFT ; + +if (range ==0 ) +return start; + +return start + (get_random_long () % range <<PAGE_SHIFT ); +} +#if defined(CONFIG_MMU ) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT )void arch_pick_mmap_layout (struct mm_struct *mm) {
Greg Kroah-Hartman
maintainerPATCH 211/264 random: convert to using fops->write_iter()
In reply to Greg Kroah-HartmanFrom: Jens Axboe <[email protected]>
commit 22b0a222af4df8ee9bb8e07013ab44da9511b047 upstream.
Now that the read side has been converted to fix a regression with splice, convert the write side as well to have some symmetry in the interface used (and help deprecate ->write()).
[Jason: cleaned up random_ioctl a bit, require full writes in
RNDADDENTROPY since it's crediting entropy, simplify control flow of write_pool(), and incorporate suggestions from Al.]
--- drivers/char/random.c | 67 ++++++++++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 32 deletions(-)
drivers/char/random.c +35 -32
@@ -1252,39 +1252,31 @@ static unsigned int random_poll(struct freturn crng_ready () ?POLLIN |POLLRDNORM :POLLOUT |POLLWRNORM ; } -static int write_pool (const char __user *ubuf,size_t len) +static ssize_t write_pool (struct iov_iter *iter) { -size_t block_len; -int ret =0 ;u8 block[BLAKE2S_BLOCK_SIZE ]; +ssize_t ret =0 ; +size_t copied; -while (len) { - block_len =min (len,sizeof (block)); -if (copy_from_user (block, ubuf, block_len)) { - ret = -EFAULT ; - goto out; - } - len -= block_len; - ubuf += block_len; -mix_pool_bytes (block, block_len); +if (unlikely (!iov_iter_count (iter))) +return 0 ; + +for (;;) { + copied =copy_from_iter (block,sizeof (block), iter); + ret += copied; +mix_pool_bytes (block, copied); +if (!iov_iter_count (iter) || copied !=sizeof (block)) +break ;cond_resched (); } -out:memzero_explicit (block,sizeof (block)); -return ret; +return ret ? ret : -EFAULT ; } -static ssize_t random_write (struct file *file,const char __user *ubuf, -size_t len,loff_t *ppos) +static ssize_t random_write_iter (struct kiocb *kiocb,struct iov_iter *iter) { -int ret; - - ret =write_pool (ubuf, len); -if (ret) -return ret; - -return (ssize_t )len; +return write_pool (iter); }static ssize_t urandom_read_iter (struct kiocb *kiocb,struct iov_iter *iter)
@@ -1316,9 +1308,8 @@ static ssize_t random_read_iter(struct kstatic long random_ioctl (struct file *f,unsigned int cmd,unsigned long arg) { -int size, ent_count;int __user *p = (int __user *)arg; -int retval; +int ent_count;switch (cmd) {case RNDGETENTCNT :
@@ -1335,20 +1326,32 @@ static long random_ioctl(struct file *f,return -EINVAL ;credit_init_bits (ent_count);return 0 ; -case RNDADDENTROPY : +case RNDADDENTROPY : { +struct iov_iter iter; +struct iovec iov; +ssize_t ret; +int len; +if (!capable (CAP_SYS_ADMIN ))return -EPERM ;if (get_user (ent_count, p++))return -EFAULT ;if (ent_count <0 )return -EINVAL ; -if (get_user (size, p++)) +if (get_user (len, p++)) +return -EFAULT ; + ret =import_single_range (WRITE , p, len, &iov, &iter); +if (unlikely (ret)) +return ret; + ret =write_pool (&iter); +if (unlikely (ret <0 )) +return ret; +/* Since we're crediting, enforce that it was all written into the pool. */ +if (unlikely (ret != len))return -EFAULT ; - retval =write_pool ((const char __user *)p, size); -if (retval <0 ) -return retval;credit_init_bits (ent_count);return 0 ; + }case RNDZAPENTCNT :case RNDCLEARPOOL :/* No longer has any effect. */
@@ -1374,7 +1377,7 @@ static int random_fasync(int fd, structconst struct file_operations random_fops = { .read_iter = random_read_iter, - .write = random_write, + .write_iter = random_write_iter, .poll = random_poll, .unlocked_ioctl = random_ioctl, .fasync = random_fasync,
@@ -1383,7 +1386,7 @@ const struct file_operations random_fopsconst struct file_operations urandom_fops = { .read_iter = urandom_read_iter, - .write = random_write, + .write_iter = random_write_iter, .unlocked_ioctl = random_ioctl, .fasync = random_fasync, .llseek = noop_llseek,