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