xref: /freebsd/sys/dev/random/fortuna.c (revision 4e462178745853ecc014c13f82f89cfe39b83e9c)
1 /*-
2  * Copyright (c) 2017 W. Dean Freeman
3  * Copyright (c) 2013-2015 Mark R V Murray
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  */
28 
29 /*
30  * This implementation of Fortuna is based on the descriptions found in
31  * ISBN 978-0-470-47424-2 "Cryptography Engineering" by Ferguson, Schneier
32  * and Kohno ("FS&K").
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include <sys/limits.h>
39 
40 #ifdef _KERNEL
41 #include <sys/param.h>
42 #include <sys/fail.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mutex.h>
47 #include <sys/random.h>
48 #include <sys/sdt.h>
49 #include <sys/sysctl.h>
50 #include <sys/systm.h>
51 
52 #include <machine/cpu.h>
53 
54 #include <crypto/rijndael/rijndael-api-fst.h>
55 #include <crypto/sha2/sha256.h>
56 
57 #include <dev/random/hash.h>
58 #include <dev/random/randomdev.h>
59 #include <dev/random/random_harvestq.h>
60 #include <dev/random/uint128.h>
61 #include <dev/random/fortuna.h>
62 #else /* !_KERNEL */
63 #include <sys/param.h>
64 #include <inttypes.h>
65 #include <stdbool.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <threads.h>
70 
71 #include "unit_test.h"
72 
73 #include <crypto/rijndael/rijndael-api-fst.h>
74 #include <crypto/sha2/sha256.h>
75 
76 #include <dev/random/hash.h>
77 #include <dev/random/randomdev.h>
78 #include <dev/random/uint128.h>
79 #include <dev/random/fortuna.h>
80 #endif /* _KERNEL */
81 
82 /* Defined in FS&K */
83 #define	RANDOM_FORTUNA_NPOOLS 32		/* The number of accumulation pools */
84 #define	RANDOM_FORTUNA_DEFPOOLSIZE 64		/* The default pool size/length for a (re)seed */
85 #define	RANDOM_FORTUNA_MAX_READ (1 << 20)	/* Max bytes in a single read */
86 
87 /*
88  * The allowable range of RANDOM_FORTUNA_DEFPOOLSIZE. The default value is above.
89  * Making RANDOM_FORTUNA_DEFPOOLSIZE too large will mean a long time between reseeds,
90  * and too small may compromise initial security but get faster reseeds.
91  */
92 #define	RANDOM_FORTUNA_MINPOOLSIZE 16
93 #define	RANDOM_FORTUNA_MAXPOOLSIZE INT_MAX
94 CTASSERT(RANDOM_FORTUNA_MINPOOLSIZE <= RANDOM_FORTUNA_DEFPOOLSIZE);
95 CTASSERT(RANDOM_FORTUNA_DEFPOOLSIZE <= RANDOM_FORTUNA_MAXPOOLSIZE);
96 
97 /* This algorithm (and code) presumes that RANDOM_KEYSIZE is twice as large as RANDOM_BLOCKSIZE */
98 CTASSERT(RANDOM_BLOCKSIZE == sizeof(uint128_t));
99 CTASSERT(RANDOM_KEYSIZE == 2*RANDOM_BLOCKSIZE);
100 
101 /* Probes for dtrace(1) */
102 #ifdef _KERNEL
103 SDT_PROVIDER_DECLARE(random);
104 SDT_PROVIDER_DEFINE(random);
105 SDT_PROBE_DEFINE2(random, fortuna, event_processor, debug, "u_int", "struct fs_pool *");
106 #endif /* _KERNEL */
107 
108 /*
109  * This is the beastie that needs protecting. It contains all of the
110  * state that we are excited about. Exactly one is instantiated.
111  */
112 static struct fortuna_state {
113 	struct fs_pool {		/* P_i */
114 		u_int fsp_length;	/* Only the first one is used by Fortuna */
115 		struct randomdev_hash fsp_hash;
116 	} fs_pool[RANDOM_FORTUNA_NPOOLS];
117 	u_int fs_reseedcount;		/* ReseedCnt */
118 	uint128_t fs_counter;		/* C */
119 	struct randomdev_key fs_key;	/* K */
120 	u_int fs_minpoolsize;		/* Extras */
121 	/* Extras for the OS */
122 #ifdef _KERNEL
123 	/* For use when 'pacing' the reseeds */
124 	sbintime_t fs_lasttime;
125 #endif
126 	/* Reseed lock */
127 	mtx_t fs_mtx;
128 } fortuna_state;
129 
130 #ifdef _KERNEL
131 static struct sysctl_ctx_list random_clist;
132 RANDOM_CHECK_UINT(fs_minpoolsize, RANDOM_FORTUNA_MINPOOLSIZE, RANDOM_FORTUNA_MAXPOOLSIZE);
133 #else
134 static uint8_t zero_region[RANDOM_ZERO_BLOCKSIZE];
135 #endif
136 
137 static void random_fortuna_pre_read(void);
138 static void random_fortuna_read(uint8_t *, u_int);
139 static bool random_fortuna_seeded(void);
140 static void random_fortuna_process_event(struct harvest_event *);
141 static void random_fortuna_init_alg(void *);
142 static void random_fortuna_deinit_alg(void *);
143 
144 static void random_fortuna_reseed_internal(uint32_t *entropy_data, u_int blockcount);
145 
146 struct random_algorithm random_alg_context = {
147 	.ra_ident = "Fortuna",
148 	.ra_init_alg = random_fortuna_init_alg,
149 	.ra_deinit_alg = random_fortuna_deinit_alg,
150 	.ra_pre_read = random_fortuna_pre_read,
151 	.ra_read = random_fortuna_read,
152 	.ra_seeded = random_fortuna_seeded,
153 	.ra_event_processor = random_fortuna_process_event,
154 	.ra_poolcount = RANDOM_FORTUNA_NPOOLS,
155 };
156 
157 /* ARGSUSED */
158 static void
159 random_fortuna_init_alg(void *unused __unused)
160 {
161 	int i;
162 #ifdef _KERNEL
163 	struct sysctl_oid *random_fortuna_o;
164 #endif
165 
166 	RANDOM_RESEED_INIT_LOCK();
167 	/*
168 	 * Fortuna parameters. Do not adjust these unless you have
169 	 * have a very good clue about what they do!
170 	 */
171 	fortuna_state.fs_minpoolsize = RANDOM_FORTUNA_DEFPOOLSIZE;
172 #ifdef _KERNEL
173 	fortuna_state.fs_lasttime = 0;
174 	random_fortuna_o = SYSCTL_ADD_NODE(&random_clist,
175 		SYSCTL_STATIC_CHILDREN(_kern_random),
176 		OID_AUTO, "fortuna", CTLFLAG_RW, 0,
177 		"Fortuna Parameters");
178 	SYSCTL_ADD_PROC(&random_clist,
179 		SYSCTL_CHILDREN(random_fortuna_o), OID_AUTO,
180 		"minpoolsize", CTLTYPE_UINT | CTLFLAG_RWTUN,
181 		&fortuna_state.fs_minpoolsize, RANDOM_FORTUNA_DEFPOOLSIZE,
182 		random_check_uint_fs_minpoolsize, "IU",
183 		"Minimum pool size necessary to cause a reseed");
184 	KASSERT(fortuna_state.fs_minpoolsize > 0, ("random: Fortuna threshold must be > 0 at startup"));
185 #endif
186 
187 	/*-
188 	 * FS&K - InitializePRNG()
189 	 *      - P_i = \epsilon
190 	 *      - ReseedCNT = 0
191 	 */
192 	for (i = 0; i < RANDOM_FORTUNA_NPOOLS; i++) {
193 		randomdev_hash_init(&fortuna_state.fs_pool[i].fsp_hash);
194 		fortuna_state.fs_pool[i].fsp_length = 0;
195 	}
196 	fortuna_state.fs_reseedcount = 0;
197 	/*-
198 	 * FS&K - InitializeGenerator()
199 	 *      - C = 0
200 	 *      - K = 0
201 	 */
202 	fortuna_state.fs_counter = UINT128_ZERO;
203 	explicit_bzero(&fortuna_state.fs_key, sizeof(fortuna_state.fs_key));
204 }
205 
206 /* ARGSUSED */
207 static void
208 random_fortuna_deinit_alg(void *unused __unused)
209 {
210 
211 	RANDOM_RESEED_DEINIT_LOCK();
212 	explicit_bzero(&fortuna_state, sizeof(fortuna_state));
213 #ifdef _KERNEL
214 	sysctl_ctx_free(&random_clist);
215 #endif
216 }
217 
218 /*-
219  * FS&K - AddRandomEvent()
220  * Process a single stochastic event off the harvest queue
221  */
222 static void
223 random_fortuna_process_event(struct harvest_event *event)
224 {
225 	u_int pl;
226 
227 	RANDOM_RESEED_LOCK();
228 	/*-
229 	 * FS&K - P_i = P_i|<harvested stuff>
230 	 * Accumulate the event into the appropriate pool
231 	 * where each event carries the destination information.
232 	 *
233 	 * The hash_init() and hash_finish() calls are done in
234 	 * random_fortuna_pre_read().
235 	 *
236 	 * We must be locked against pool state modification which can happen
237 	 * during accumulation/reseeding and reading/regating.
238 	 */
239 	pl = event->he_destination % RANDOM_FORTUNA_NPOOLS;
240 	/*
241 	 * We ignore low entropy static/counter fields towards the end of the
242 	 * he_event structure in order to increase measurable entropy when
243 	 * conducting SP800-90B entropy analysis measurements of seed material
244 	 * fed into PRNG.
245 	 * -- wdf
246 	 */
247 	KASSERT(event->he_size <= sizeof(event->he_entropy),
248 	    ("%s: event->he_size: %hhu > sizeof(event->he_entropy): %zu\n",
249 	    __func__, event->he_size, sizeof(event->he_entropy)));
250 	randomdev_hash_iterate(&fortuna_state.fs_pool[pl].fsp_hash,
251 	    &event->he_somecounter, sizeof(event->he_somecounter));
252 	randomdev_hash_iterate(&fortuna_state.fs_pool[pl].fsp_hash,
253 	    event->he_entropy, event->he_size);
254 
255 	/*-
256 	 * Don't wrap the length.  This is a "saturating" add.
257 	 * XXX: FIX!!: We don't actually need lengths for anything but fs_pool[0],
258 	 * but it's been useful debugging to see them all.
259 	 */
260 	fortuna_state.fs_pool[pl].fsp_length = MIN(RANDOM_FORTUNA_MAXPOOLSIZE,
261 	    fortuna_state.fs_pool[pl].fsp_length +
262 	    sizeof(event->he_somecounter) + event->he_size);
263 	explicit_bzero(event, sizeof(*event));
264 	RANDOM_RESEED_UNLOCK();
265 }
266 
267 /*-
268  * FS&K - Reseed()
269  * This introduces new key material into the output generator.
270  * Additionally it increments the output generator's counter
271  * variable C. When C > 0, the output generator is seeded and
272  * will deliver output.
273  * The entropy_data buffer passed is a very specific size; the
274  * product of RANDOM_FORTUNA_NPOOLS and RANDOM_KEYSIZE.
275  */
276 static void
277 random_fortuna_reseed_internal(uint32_t *entropy_data, u_int blockcount)
278 {
279 	struct randomdev_hash context;
280 	uint8_t hash[RANDOM_KEYSIZE];
281 
282 	RANDOM_RESEED_ASSERT_LOCK_OWNED();
283 	/*-
284 	 * FS&K - K = Hd(K|s) where Hd(m) is H(H(0^512|m))
285 	 *      - C = C + 1
286 	 */
287 	randomdev_hash_init(&context);
288 	randomdev_hash_iterate(&context, zero_region, RANDOM_ZERO_BLOCKSIZE);
289 	randomdev_hash_iterate(&context, &fortuna_state.fs_key.key.keyMaterial,
290 	    fortuna_state.fs_key.key.keyLen / 8);
291 	randomdev_hash_iterate(&context, entropy_data, RANDOM_KEYSIZE*blockcount);
292 	randomdev_hash_finish(&context, hash);
293 	randomdev_hash_init(&context);
294 	randomdev_hash_iterate(&context, hash, RANDOM_KEYSIZE);
295 	randomdev_hash_finish(&context, hash);
296 	randomdev_encrypt_init(&fortuna_state.fs_key, hash);
297 	explicit_bzero(hash, sizeof(hash));
298 	/* Unblock the device if this is the first time we are reseeding. */
299 	if (uint128_is_zero(fortuna_state.fs_counter))
300 		randomdev_unblock();
301 	uint128_increment(&fortuna_state.fs_counter);
302 }
303 
304 /*-
305  * FS&K - GenerateBlocks()
306  * Generate a number of complete blocks of random output.
307  */
308 static __inline void
309 random_fortuna_genblocks(uint8_t *buf, u_int blockcount)
310 {
311 	u_int i;
312 
313 	RANDOM_RESEED_ASSERT_LOCK_OWNED();
314 	KASSERT(!uint128_is_zero(fortuna_state.fs_counter), ("FS&K: C != 0"));
315 
316 	for (i = 0; i < blockcount; i++) {
317 		/*-
318 		 * FS&K - r = r|E(K,C)
319 		 *      - C = C + 1
320 		 */
321 		randomdev_encrypt(&fortuna_state.fs_key, &fortuna_state.fs_counter, buf, RANDOM_BLOCKSIZE);
322 		buf += RANDOM_BLOCKSIZE;
323 		uint128_increment(&fortuna_state.fs_counter);
324 	}
325 }
326 
327 /*-
328  * FS&K - PseudoRandomData()
329  * This generates no more than 2^20 bytes of data, and cleans up its
330  * internal state when finished. It is assumed that a whole number of
331  * blocks are available for writing; any excess generated will be
332  * ignored.
333  */
334 static __inline void
335 random_fortuna_genrandom(uint8_t *buf, u_int bytecount)
336 {
337 	uint8_t temp[RANDOM_BLOCKSIZE * RANDOM_KEYS_PER_BLOCK];
338 	u_int blockcount;
339 
340 	RANDOM_RESEED_ASSERT_LOCK_OWNED();
341 	/*-
342 	 * FS&K - assert(n < 2^20 (== 1 MB)
343 	 *      - r = first-n-bytes(GenerateBlocks(ceil(n/16)))
344 	 *      - K = GenerateBlocks(2)
345 	 */
346 	KASSERT((bytecount <= RANDOM_FORTUNA_MAX_READ), ("invalid single read request to Fortuna of %d bytes", bytecount));
347 	blockcount = howmany(bytecount, RANDOM_BLOCKSIZE);
348 	random_fortuna_genblocks(buf, blockcount);
349 	random_fortuna_genblocks(temp, RANDOM_KEYS_PER_BLOCK);
350 	randomdev_encrypt_init(&fortuna_state.fs_key, temp);
351 	explicit_bzero(temp, sizeof(temp));
352 }
353 
354 /*-
355  * FS&K - RandomData() (Part 1)
356  * Used to return processed entropy from the PRNG. There is a pre_read
357  * required to be present (but it can be a stub) in order to allow
358  * specific actions at the begin of the read.
359  */
360 void
361 random_fortuna_pre_read(void)
362 {
363 #ifdef _KERNEL
364 	sbintime_t now;
365 #endif
366 	struct randomdev_hash context;
367 	uint32_t s[RANDOM_FORTUNA_NPOOLS*RANDOM_KEYSIZE_WORDS];
368 	uint8_t temp[RANDOM_KEYSIZE];
369 	u_int i;
370 
371 	KASSERT(fortuna_state.fs_minpoolsize > 0, ("random: Fortuna threshold must be > 0"));
372 	RANDOM_RESEED_LOCK();
373 #ifdef _KERNEL
374 	/* FS&K - Use 'getsbinuptime()' to prevent reseed-spamming. */
375 	now = getsbinuptime();
376 #endif
377 
378 	if (fortuna_state.fs_pool[0].fsp_length < fortuna_state.fs_minpoolsize
379 #ifdef _KERNEL
380 	    /* FS&K - Use 'getsbinuptime()' to prevent reseed-spamming. */
381 	    || (now - fortuna_state.fs_lasttime <= SBT_1S/10)
382 #endif
383 	) {
384 		RANDOM_RESEED_UNLOCK();
385 		return;
386 	}
387 
388 #ifdef _KERNEL
389 	/*
390 	 * When set, pretend we do not have enough entropy to reseed yet.
391 	 */
392 	KFAIL_POINT_CODE(DEBUG_FP, random_fortuna_pre_read, {
393 		if (RETURN_VALUE != 0) {
394 			RANDOM_RESEED_UNLOCK();
395 			return;
396 		}
397 	});
398 #endif
399 
400 #ifdef _KERNEL
401 	fortuna_state.fs_lasttime = now;
402 #endif
403 
404 	/* FS&K - ReseedCNT = ReseedCNT + 1 */
405 	fortuna_state.fs_reseedcount++;
406 	/* s = \epsilon at start */
407 	for (i = 0; i < RANDOM_FORTUNA_NPOOLS; i++) {
408 		/* FS&K - if Divides(ReseedCnt, 2^i) ... */
409 		if ((fortuna_state.fs_reseedcount % (1 << i)) == 0) {
410 			/*-
411 			    * FS&K - temp = (P_i)
412 			    *      - P_i = \epsilon
413 			    *      - s = s|H(temp)
414 			    */
415 			randomdev_hash_finish(&fortuna_state.fs_pool[i].fsp_hash, temp);
416 			randomdev_hash_init(&fortuna_state.fs_pool[i].fsp_hash);
417 			fortuna_state.fs_pool[i].fsp_length = 0;
418 			randomdev_hash_init(&context);
419 			randomdev_hash_iterate(&context, temp, RANDOM_KEYSIZE);
420 			randomdev_hash_finish(&context, s + i*RANDOM_KEYSIZE_WORDS);
421 		} else
422 			break;
423 	}
424 #ifdef _KERNEL
425 	SDT_PROBE2(random, fortuna, event_processor, debug, fortuna_state.fs_reseedcount, fortuna_state.fs_pool);
426 #endif
427 	/* FS&K */
428 	random_fortuna_reseed_internal(s, i);
429 	RANDOM_RESEED_UNLOCK();
430 
431 	/* Clean up and secure */
432 	explicit_bzero(s, sizeof(s));
433 	explicit_bzero(temp, sizeof(temp));
434 }
435 
436 /*-
437  * FS&K - RandomData() (Part 2)
438  * Main read from Fortuna, continued. May be called multiple times after
439  * the random_fortuna_pre_read() above.
440  * The supplied buf MUST be a multiple of RANDOM_BLOCKSIZE in size.
441  * Lots of code presumes this for efficiency, both here and in other
442  * routines. You are NOT allowed to break this!
443  */
444 void
445 random_fortuna_read(uint8_t *buf, u_int bytecount)
446 {
447 
448 	KASSERT((bytecount % RANDOM_BLOCKSIZE) == 0, ("%s(): bytecount (= %d) must be a multiple of %d", __func__, bytecount, RANDOM_BLOCKSIZE ));
449 	RANDOM_RESEED_LOCK();
450 	random_fortuna_genrandom(buf, bytecount);
451 	RANDOM_RESEED_UNLOCK();
452 }
453 
454 bool
455 random_fortuna_seeded(void)
456 {
457 
458 #ifdef _KERNEL
459 	/* When set, act as if we are not seeded. */
460 	KFAIL_POINT_CODE(DEBUG_FP, random_fortuna_seeded, {
461 		if (RETURN_VALUE != 0)
462 			fortuna_state.fs_counter = UINT128_ZERO;
463 	});
464 #endif
465 
466 	return (!uint128_is_zero(fortuna_state.fs_counter));
467 }
468