]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - lib/random32.c
random32: make prandom_u32() output unpredictable
[mirror_ubuntu-jammy-kernel.git] / lib / random32.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
aaa248f6 2/*
d3d47eb2
DB
3 * This is a maximally equidistributed combined Tausworthe generator
4 * based on code from GNU Scientific Library 1.5 (30 Jun 2004)
5 *
6 * lfsr113 version:
7 *
8 * x_n = (s1_n ^ s2_n ^ s3_n ^ s4_n)
9 *
10 * s1_{n+1} = (((s1_n & 4294967294) << 18) ^ (((s1_n << 6) ^ s1_n) >> 13))
11 * s2_{n+1} = (((s2_n & 4294967288) << 2) ^ (((s2_n << 2) ^ s2_n) >> 27))
12 * s3_{n+1} = (((s3_n & 4294967280) << 7) ^ (((s3_n << 13) ^ s3_n) >> 21))
13 * s4_{n+1} = (((s4_n & 4294967168) << 13) ^ (((s4_n << 3) ^ s4_n) >> 12))
14 *
15 * The period of this generator is about 2^113 (see erratum paper).
16 *
17 * From: P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe
18 * Generators", Mathematics of Computation, 65, 213 (1996), 203--213:
19 * http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps
20 * ftp://ftp.iro.umontreal.ca/pub/simulation/lecuyer/papers/tausme.ps
21 *
22 * There is an erratum in the paper "Tables of Maximally Equidistributed
23 * Combined LFSR Generators", Mathematics of Computation, 68, 225 (1999),
24 * 261--269: http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
25 *
26 * ... the k_j most significant bits of z_j must be non-zero,
27 * for each j. (Note: this restriction also applies to the
28 * computer code given in [4], but was mistakenly not mentioned
29 * in that paper.)
30 *
31 * This affects the seeding procedure by imposing the requirement
32 * s1 > 1, s2 > 7, s3 > 15, s4 > 127.
33 */
aaa248f6
SH
34
35#include <linux/types.h>
36#include <linux/percpu.h>
8bc3bcc9 37#include <linux/export.h>
f6a57033 38#include <linux/jiffies.h>
aaa248f6 39#include <linux/random.h>
a6a9c0f1 40#include <linux/sched.h>
a98406e2 41#include <asm/unaligned.h>
94c7eb54 42#include <trace/events/random.h>
a6a9c0f1 43
5960164f 44/**
496f2f93 45 * prandom_u32_state - seeded pseudo-random number generator.
5960164f
JE
46 * @state: pointer to state structure holding seeded state.
47 *
48 * This is used for pseudo-randomness with no outside seeding.
496f2f93 49 * For more random results, use prandom_u32().
5960164f 50 */
496f2f93 51u32 prandom_u32_state(struct rnd_state *state)
aaa248f6 52{
4ada97ab 53#define TAUSWORTHE(s, a, b, c, d) ((s & c) << d) ^ (((s << a) ^ s) >> b)
a98814ce
DB
54 state->s1 = TAUSWORTHE(state->s1, 6U, 13U, 4294967294U, 18U);
55 state->s2 = TAUSWORTHE(state->s2, 2U, 27U, 4294967288U, 2U);
56 state->s3 = TAUSWORTHE(state->s3, 13U, 21U, 4294967280U, 7U);
57 state->s4 = TAUSWORTHE(state->s4, 3U, 12U, 4294967168U, 13U);
aaa248f6 58
a98814ce 59 return (state->s1 ^ state->s2 ^ state->s3 ^ state->s4);
aaa248f6 60}
496f2f93 61EXPORT_SYMBOL(prandom_u32_state);
aaa248f6 62
d3d47eb2 63/**
6582c665
AM
64 * prandom_bytes_state - get the requested number of pseudo-random bytes
65 *
66 * @state: pointer to state structure holding seeded state.
67 * @buf: where to copy the pseudo-random bytes to
68 * @bytes: the requested number of bytes
69 *
70 * This is used for pseudo-randomness with no outside seeding.
71 * For more random results, use prandom_bytes().
72 */
a98406e2 73void prandom_bytes_state(struct rnd_state *state, void *buf, size_t bytes)
6582c665 74{
a98406e2 75 u8 *ptr = buf;
6582c665 76
a98406e2
DB
77 while (bytes >= sizeof(u32)) {
78 put_unaligned(prandom_u32_state(state), (u32 *) ptr);
79 ptr += sizeof(u32);
80 bytes -= sizeof(u32);
6582c665 81 }
6582c665 82
a98406e2
DB
83 if (bytes > 0) {
84 u32 rem = prandom_u32_state(state);
85 do {
86 *ptr++ = (u8) rem;
87 bytes--;
88 rem >>= BITS_PER_BYTE;
89 } while (bytes > 0);
6582c665
AM
90 }
91}
92EXPORT_SYMBOL(prandom_bytes_state);
93
a98814ce
DB
94static void prandom_warmup(struct rnd_state *state)
95{
a98406e2 96 /* Calling RNG ten times to satisfy recurrence condition */
a98814ce
DB
97 prandom_u32_state(state);
98 prandom_u32_state(state);
99 prandom_u32_state(state);
100 prandom_u32_state(state);
101 prandom_u32_state(state);
102 prandom_u32_state(state);
103 prandom_u32_state(state);
104 prandom_u32_state(state);
105 prandom_u32_state(state);
106 prandom_u32_state(state);
107}
108
897ece56 109void prandom_seed_full_state(struct rnd_state __percpu *pcpu_state)
0dd50d1b
DB
110{
111 int i;
112
113 for_each_possible_cpu(i) {
114 struct rnd_state *state = per_cpu_ptr(pcpu_state, i);
115 u32 seeds[4];
116
117 get_random_bytes(&seeds, sizeof(seeds));
118 state->s1 = __seed(seeds[0], 2U);
119 state->s2 = __seed(seeds[1], 8U);
120 state->s3 = __seed(seeds[2], 16U);
121 state->s4 = __seed(seeds[3], 128U);
122
123 prandom_warmup(state);
124 }
125}
b07edbe1 126EXPORT_SYMBOL(prandom_seed_full_state);
0dd50d1b 127
a6a9c0f1
DB
128#ifdef CONFIG_RANDOM32_SELFTEST
129static struct prandom_test1 {
130 u32 seed;
131 u32 result;
132} test1[] = {
133 { 1U, 3484351685U },
134 { 2U, 2623130059U },
135 { 3U, 3125133893U },
136 { 4U, 984847254U },
137};
138
139static struct prandom_test2 {
140 u32 seed;
141 u32 iteration;
142 u32 result;
143} test2[] = {
144 /* Test cases against taus113 from GSL library. */
145 { 931557656U, 959U, 2975593782U },
146 { 1339693295U, 876U, 3887776532U },
147 { 1545556285U, 961U, 1615538833U },
148 { 601730776U, 723U, 1776162651U },
149 { 1027516047U, 687U, 511983079U },
150 { 416526298U, 700U, 916156552U },
151 { 1395522032U, 652U, 2222063676U },
152 { 366221443U, 617U, 2992857763U },
153 { 1539836965U, 714U, 3783265725U },
154 { 556206671U, 994U, 799626459U },
155 { 684907218U, 799U, 367789491U },
156 { 2121230701U, 931U, 2115467001U },
157 { 1668516451U, 644U, 3620590685U },
158 { 768046066U, 883U, 2034077390U },
159 { 1989159136U, 833U, 1195767305U },
160 { 536585145U, 996U, 3577259204U },
161 { 1008129373U, 642U, 1478080776U },
162 { 1740775604U, 939U, 1264980372U },
163 { 1967883163U, 508U, 10734624U },
164 { 1923019697U, 730U, 3821419629U },
165 { 442079932U, 560U, 3440032343U },
166 { 1961302714U, 845U, 841962572U },
167 { 2030205964U, 962U, 1325144227U },
168 { 1160407529U, 507U, 240940858U },
169 { 635482502U, 779U, 4200489746U },
170 { 1252788931U, 699U, 867195434U },
171 { 1961817131U, 719U, 668237657U },
172 { 1071468216U, 983U, 917876630U },
173 { 1281848367U, 932U, 1003100039U },
174 { 582537119U, 780U, 1127273778U },
175 { 1973672777U, 853U, 1071368872U },
176 { 1896756996U, 762U, 1127851055U },
177 { 847917054U, 500U, 1717499075U },
178 { 1240520510U, 951U, 2849576657U },
179 { 1685071682U, 567U, 1961810396U },
180 { 1516232129U, 557U, 3173877U },
181 { 1208118903U, 612U, 1613145022U },
182 { 1817269927U, 693U, 4279122573U },
183 { 1510091701U, 717U, 638191229U },
184 { 365916850U, 807U, 600424314U },
185 { 399324359U, 702U, 1803598116U },
186 { 1318480274U, 779U, 2074237022U },
187 { 697758115U, 840U, 1483639402U },
188 { 1696507773U, 840U, 577415447U },
189 { 2081979121U, 981U, 3041486449U },
190 { 955646687U, 742U, 3846494357U },
191 { 1250683506U, 749U, 836419859U },
192 { 595003102U, 534U, 366794109U },
193 { 47485338U, 558U, 3521120834U },
194 { 619433479U, 610U, 3991783875U },
195 { 704096520U, 518U, 4139493852U },
196 { 1712224984U, 606U, 2393312003U },
197 { 1318233152U, 922U, 3880361134U },
198 { 855572992U, 761U, 1472974787U },
199 { 64721421U, 703U, 683860550U },
200 { 678931758U, 840U, 380616043U },
201 { 692711973U, 778U, 1382361947U },
202 { 677703619U, 530U, 2826914161U },
203 { 92393223U, 586U, 1522128471U },
204 { 1222592920U, 743U, 3466726667U },
205 { 358288986U, 695U, 1091956998U },
206 { 1935056945U, 958U, 514864477U },
207 { 735675993U, 990U, 1294239989U },
208 { 1560089402U, 897U, 2238551287U },
209 { 70616361U, 829U, 22483098U },
210 { 368234700U, 731U, 2913875084U },
211 { 20221190U, 879U, 1564152970U },
212 { 539444654U, 682U, 1835141259U },
213 { 1314987297U, 840U, 1801114136U },
214 { 2019295544U, 645U, 3286438930U },
215 { 469023838U, 716U, 1637918202U },
216 { 1843754496U, 653U, 2562092152U },
217 { 400672036U, 809U, 4264212785U },
218 { 404722249U, 965U, 2704116999U },
219 { 600702209U, 758U, 584979986U },
220 { 519953954U, 667U, 2574436237U },
221 { 1658071126U, 694U, 2214569490U },
222 { 420480037U, 749U, 3430010866U },
223 { 690103647U, 969U, 3700758083U },
224 { 1029424799U, 937U, 3787746841U },
225 { 2012608669U, 506U, 3362628973U },
226 { 1535432887U, 998U, 42610943U },
227 { 1330635533U, 857U, 3040806504U },
228 { 1223800550U, 539U, 3954229517U },
229 { 1322411537U, 680U, 3223250324U },
230 { 1877847898U, 945U, 2915147143U },
231 { 1646356099U, 874U, 965988280U },
232 { 805687536U, 744U, 4032277920U },
233 { 1948093210U, 633U, 1346597684U },
234 { 392609744U, 783U, 1636083295U },
235 { 690241304U, 770U, 1201031298U },
236 { 1360302965U, 696U, 1665394461U },
237 { 1220090946U, 780U, 1316922812U },
238 { 447092251U, 500U, 3438743375U },
239 { 1613868791U, 592U, 828546883U },
240 { 523430951U, 548U, 2552392304U },
241 { 726692899U, 810U, 1656872867U },
242 { 1364340021U, 836U, 3710513486U },
243 { 1986257729U, 931U, 935013962U },
244 { 407983964U, 921U, 728767059U },
245};
246
c51f8f88
GS
247static u32 __extract_hwseed(void)
248{
249 unsigned int val = 0;
250
251 (void)(arch_get_random_seed_int(&val) ||
252 arch_get_random_int(&val));
253
254 return val;
255}
256
257static void prandom_seed_early(struct rnd_state *state, u32 seed,
258 bool mix_with_hwseed)
259{
260#define LCG(x) ((x) * 69069U) /* super-duper LCG */
261#define HWSEED() (mix_with_hwseed ? __extract_hwseed() : 0)
262 state->s1 = __seed(HWSEED() ^ LCG(seed), 2U);
263 state->s2 = __seed(HWSEED() ^ LCG(state->s1), 8U);
264 state->s3 = __seed(HWSEED() ^ LCG(state->s2), 16U);
265 state->s4 = __seed(HWSEED() ^ LCG(state->s3), 128U);
266}
267
268static int __init prandom_state_selftest(void)
a6a9c0f1
DB
269{
270 int i, j, errors = 0, runs = 0;
271 bool error = false;
272
273 for (i = 0; i < ARRAY_SIZE(test1); i++) {
274 struct rnd_state state;
275
4ada97ab 276 prandom_seed_early(&state, test1[i].seed, false);
a6a9c0f1
DB
277 prandom_warmup(&state);
278
279 if (test1[i].result != prandom_u32_state(&state))
280 error = true;
281 }
282
283 if (error)
284 pr_warn("prandom: seed boundary self test failed\n");
285 else
286 pr_info("prandom: seed boundary self test passed\n");
287
288 for (i = 0; i < ARRAY_SIZE(test2); i++) {
289 struct rnd_state state;
290
4ada97ab 291 prandom_seed_early(&state, test2[i].seed, false);
a6a9c0f1
DB
292 prandom_warmup(&state);
293
294 for (j = 0; j < test2[i].iteration - 1; j++)
295 prandom_u32_state(&state);
296
297 if (test2[i].result != prandom_u32_state(&state))
298 errors++;
299
300 runs++;
301 cond_resched();
302 }
303
304 if (errors)
305 pr_warn("prandom: %d/%d self tests failed\n", errors, runs);
306 else
307 pr_info("prandom: %d self tests passed\n", runs);
c51f8f88 308 return 0;
a6a9c0f1 309}
c51f8f88 310core_initcall(prandom_state_selftest);
a6a9c0f1 311#endif
c51f8f88
GS
312
313/*
314 * The prandom_u32() implementation is now completely separate from the
315 * prandom_state() functions, which are retained (for now) for compatibility.
316 *
317 * Because of (ab)use in the networking code for choosing random TCP/UDP port
318 * numbers, which open DoS possibilities if guessable, we want something
319 * stronger than a standard PRNG. But the performance requirements of
320 * the network code do not allow robust crypto for this application.
321 *
322 * So this is a homebrew Junior Spaceman implementation, based on the
323 * lowest-latency trustworthy crypto primitive available, SipHash.
324 * (The authors of SipHash have not been consulted about this abuse of
325 * their work.)
326 *
327 * Standard SipHash-2-4 uses 2n+4 rounds to hash n words of input to
328 * one word of output. This abbreviated version uses 2 rounds per word
329 * of output.
330 */
331
332struct siprand_state {
333 unsigned long v0;
334 unsigned long v1;
335 unsigned long v2;
336 unsigned long v3;
337};
338
339static DEFINE_PER_CPU(struct siprand_state, net_rand_state) __latent_entropy;
340
341/*
342 * This is the core CPRNG function. As "pseudorandom", this is not used
343 * for truly valuable things, just intended to be a PITA to guess.
344 * For maximum speed, we do just two SipHash rounds per word. This is
345 * the same rate as 4 rounds per 64 bits that SipHash normally uses,
346 * so hopefully it's reasonably secure.
347 *
348 * There are two changes from the official SipHash finalization:
349 * - We omit some constants XORed with v2 in the SipHash spec as irrelevant;
350 * they are there only to make the output rounds distinct from the input
351 * rounds, and this application has no input rounds.
352 * - Rather than returning v0^v1^v2^v3, return v1+v3.
353 * If you look at the SipHash round, the last operation on v3 is
354 * "v3 ^= v0", so "v0 ^ v3" just undoes that, a waste of time.
355 * Likewise "v1 ^= v2". (The rotate of v2 makes a difference, but
356 * it still cancels out half of the bits in v2 for no benefit.)
357 * Second, since the last combining operation was xor, continue the
358 * pattern of alternating xor/add for a tiny bit of extra non-linearity.
359 */
360static inline u32 siprand_u32(struct siprand_state *s)
361{
362 unsigned long v0 = s->v0, v1 = s->v1, v2 = s->v2, v3 = s->v3;
363
364 PRND_SIPROUND(v0, v1, v2, v3);
365 PRND_SIPROUND(v0, v1, v2, v3);
366 s->v0 = v0; s->v1 = v1; s->v2 = v2; s->v3 = v3;
367 return v1 + v3;
368}
369
370
371/**
372 * prandom_u32 - pseudo random number generator
373 *
374 * A 32 bit pseudo-random number is generated using a fast
375 * algorithm suitable for simulation. This algorithm is NOT
376 * considered safe for cryptographic use.
377 */
378u32 prandom_u32(void)
379{
380 struct siprand_state *state = get_cpu_ptr(&net_rand_state);
381 u32 res = siprand_u32(state);
382
383 trace_prandom_u32(res);
384 put_cpu_ptr(&net_rand_state);
385 return res;
386}
387EXPORT_SYMBOL(prandom_u32);
388
389/**
390 * prandom_bytes - get the requested number of pseudo-random bytes
391 * @buf: where to copy the pseudo-random bytes to
392 * @bytes: the requested number of bytes
393 */
394void prandom_bytes(void *buf, size_t bytes)
395{
396 struct siprand_state *state = get_cpu_ptr(&net_rand_state);
397 u8 *ptr = buf;
398
399 while (bytes >= sizeof(u32)) {
400 put_unaligned(siprand_u32(state), (u32 *)ptr);
401 ptr += sizeof(u32);
402 bytes -= sizeof(u32);
403 }
404
405 if (bytes > 0) {
406 u32 rem = siprand_u32(state);
407
408 do {
409 *ptr++ = (u8)rem;
410 rem >>= BITS_PER_BYTE;
411 } while (--bytes > 0);
412 }
413 put_cpu_ptr(&net_rand_state);
414}
415EXPORT_SYMBOL(prandom_bytes);
416
417/**
418 * prandom_seed - add entropy to pseudo random number generator
419 * @entropy: entropy value
420 *
421 * Add some additional seed material to the prandom pool.
422 * The "entropy" is actually our IP address (the only caller is
423 * the network code), not for unpredictability, but to ensure that
424 * different machines are initialized differently.
425 */
426void prandom_seed(u32 entropy)
427{
428 int i;
429
430 add_device_randomness(&entropy, sizeof(entropy));
431
432 for_each_possible_cpu(i) {
433 struct siprand_state *state = per_cpu_ptr(&net_rand_state, i);
434 unsigned long v0 = state->v0, v1 = state->v1;
435 unsigned long v2 = state->v2, v3 = state->v3;
436
437 do {
438 v3 ^= entropy;
439 PRND_SIPROUND(v0, v1, v2, v3);
440 PRND_SIPROUND(v0, v1, v2, v3);
441 v0 ^= entropy;
442 } while (unlikely(!v0 || !v1 || !v2 || !v3));
443
444 WRITE_ONCE(state->v0, v0);
445 WRITE_ONCE(state->v1, v1);
446 WRITE_ONCE(state->v2, v2);
447 WRITE_ONCE(state->v3, v3);
448 }
449}
450EXPORT_SYMBOL(prandom_seed);
451
452/*
453 * Generate some initially weak seeding values to allow
454 * the prandom_u32() engine to be started.
455 */
456static int __init prandom_init_early(void)
457{
458 int i;
459 unsigned long v0, v1, v2, v3;
460
461 if (!arch_get_random_long(&v0))
462 v0 = jiffies;
463 if (!arch_get_random_long(&v1))
464 v1 = random_get_entropy();
465 v2 = v0 ^ PRND_K0;
466 v3 = v1 ^ PRND_K1;
467
468 for_each_possible_cpu(i) {
469 struct siprand_state *state;
470
471 v3 ^= i;
472 PRND_SIPROUND(v0, v1, v2, v3);
473 PRND_SIPROUND(v0, v1, v2, v3);
474 v0 ^= i;
475
476 state = per_cpu_ptr(&net_rand_state, i);
477 state->v0 = v0; state->v1 = v1;
478 state->v2 = v2; state->v3 = v3;
479 }
480
481 return 0;
482}
483core_initcall(prandom_init_early);
484
485
486/* Stronger reseeding when available, and periodically thereafter. */
487static void prandom_reseed(struct timer_list *unused);
488
489static DEFINE_TIMER(seed_timer, prandom_reseed);
490
491static void prandom_reseed(struct timer_list *unused)
492{
493 unsigned long expires;
494 int i;
495
496 /*
497 * Reinitialize each CPU's PRNG with 128 bits of key.
498 * No locking on the CPUs, but then somewhat random results are,
499 * well, expected.
500 */
501 for_each_possible_cpu(i) {
502 struct siprand_state *state;
503 unsigned long v0 = get_random_long(), v2 = v0 ^ PRND_K0;
504 unsigned long v1 = get_random_long(), v3 = v1 ^ PRND_K1;
505#if BITS_PER_LONG == 32
506 int j;
507
508 /*
509 * On 32-bit machines, hash in two extra words to
510 * approximate 128-bit key length. Not that the hash
511 * has that much security, but this prevents a trivial
512 * 64-bit brute force.
513 */
514 for (j = 0; j < 2; j++) {
515 unsigned long m = get_random_long();
516
517 v3 ^= m;
518 PRND_SIPROUND(v0, v1, v2, v3);
519 PRND_SIPROUND(v0, v1, v2, v3);
520 v0 ^= m;
521 }
522#endif
523 /*
524 * Probably impossible in practice, but there is a
525 * theoretical risk that a race between this reseeding
526 * and the target CPU writing its state back could
527 * create the all-zero SipHash fixed point.
528 *
529 * To ensure that never happens, ensure the state
530 * we write contains no zero words.
531 */
532 state = per_cpu_ptr(&net_rand_state, i);
533 WRITE_ONCE(state->v0, v0 ? v0 : -1ul);
534 WRITE_ONCE(state->v1, v1 ? v1 : -1ul);
535 WRITE_ONCE(state->v2, v2 ? v2 : -1ul);
536 WRITE_ONCE(state->v3, v3 ? v3 : -1ul);
537 }
538
539 /* reseed every ~60 seconds, in [40 .. 80) interval with slack */
540 expires = round_jiffies(jiffies + 40 * HZ + prandom_u32_max(40 * HZ));
541 mod_timer(&seed_timer, expires);
542}
543
544/*
545 * The random ready callback can be called from almost any interrupt.
546 * To avoid worrying about whether it's safe to delay that interrupt
547 * long enough to seed all CPUs, just schedule an immediate timer event.
548 */
549static void prandom_timer_start(struct random_ready_callback *unused)
550{
551 mod_timer(&seed_timer, jiffies);
552}
553
554/*
555 * Start periodic full reseeding as soon as strong
556 * random numbers are available.
557 */
558static int __init prandom_init_late(void)
559{
560 static struct random_ready_callback random_ready = {
561 .func = prandom_timer_start
562 };
563 int ret = add_random_ready_callback(&random_ready);
564
565 if (ret == -EALREADY) {
566 prandom_timer_start(&random_ready);
567 ret = 0;
568 }
569 return ret;
570}
571late_initcall(prandom_init_late);