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