1 /*
2  * fortuna.c
3  *		Fortuna-like PRNG.
4  *
5  * Copyright (c) 2005 Marko Kreen
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *	  notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *	  notice, this list of conditions and the following disclaimer in the
15  *	  documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * contrib/pgcrypto/fortuna.c
30  */
31 
32 #include "postgres.h"
33 
34 #include <sys/time.h>
35 #include <time.h>
36 
37 #include "px.h"
38 #include "rijndael.h"
39 #include "sha2.h"
40 #include "fortuna.h"
41 
42 
43 /*
44  * Why Fortuna-like: There does not seem to be any definitive reference
45  * on Fortuna in the net.  Instead this implementation is based on
46  * following references:
47  *
48  * http://en.wikipedia.org/wiki/Fortuna_(PRNG)
49  *	 - Wikipedia article
50  * http://jlcooke.ca/random/
51  *	 - Jean-Luc Cooke Fortuna-based /dev/random driver for Linux.
52  */
53 
54 /*
55  * There is some confusion about whether and how to carry forward
56  * the state of the pools.  Seems like original Fortuna does not
57  * do it, resetting hash after each request.  I guess expecting
58  * feeding to happen more often that requesting.   This is absolutely
59  * unsuitable for pgcrypto, as nothing asynchronous happens here.
60  *
61  * J.L. Cooke fixed this by feeding previous hash to new re-initialized
62  * hash context.
63  *
64  * Fortuna predecessor Yarrow requires ability to query intermediate
65  * 'final result' from hash, without affecting it.
66  *
67  * This implementation uses the Yarrow method - asking intermediate
68  * results, but continuing with old state.
69  */
70 
71 
72 /*
73  * Algorithm parameters
74  */
75 
76 /*
77  * How many pools.
78  *
79  * Original Fortuna uses 32 pools, that means 32'th pool is
80  * used not earlier than in 13th year.  This is a waste in
81  * pgcrypto, as we have very low-frequancy seeding.  Here
82  * is preferable to have all entropy usable in reasonable time.
83  *
84  * With 23 pools, 23th pool is used after 9 days which seems
85  * more sane.
86  *
87  * In our case the minimal cycle time would be bit longer
88  * than the system-randomness feeding frequency.
89  */
90 #define NUM_POOLS		23
91 
92 /* in microseconds */
93 #define RESEED_INTERVAL 100000	/* 0.1 sec */
94 
95 /* for one big request, reseed after this many bytes */
96 #define RESEED_BYTES	(1024*1024)
97 
98 /*
99  * Skip reseed if pool 0 has less than this many
100  * bytes added since last reseed.
101  */
102 #define POOL0_FILL		(256/8)
103 
104 /*
105  * Algorithm constants
106  */
107 
108 /* Both cipher key size and hash result size */
109 #define BLOCK			32
110 
111 /* cipher block size */
112 #define CIPH_BLOCK		16
113 
114 /* for internal wrappers */
115 #define MD_CTX			SHA256_CTX
116 #define CIPH_CTX		rijndael_ctx
117 
118 struct fortuna_state
119 {
120 	uint8		counter[CIPH_BLOCK];
121 	uint8		result[CIPH_BLOCK];
122 	uint8		key[BLOCK];
123 	MD_CTX		pool[NUM_POOLS];
124 	CIPH_CTX	ciph;
125 	unsigned	reseed_count;
126 	struct timeval last_reseed_time;
127 	unsigned	pool0_bytes;
128 	unsigned	rnd_pos;
129 	int			tricks_done;
130 };
131 typedef struct fortuna_state FState;
132 
133 
134 /*
135  * Use our own wrappers here.
136  * - Need to get intermediate result from digest, without affecting it.
137  * - Need re-set key on a cipher context.
138  * - Algorithms are guaranteed to exist.
139  * - No memory allocations.
140  */
141 
142 static void
ciph_init(CIPH_CTX * ctx,const uint8 * key,int klen)143 ciph_init(CIPH_CTX * ctx, const uint8 *key, int klen)
144 {
145 	rijndael_set_key(ctx, (const uint32 *) key, klen, 1);
146 }
147 
148 static void
ciph_encrypt(CIPH_CTX * ctx,const uint8 * in,uint8 * out)149 ciph_encrypt(CIPH_CTX * ctx, const uint8 *in, uint8 *out)
150 {
151 	rijndael_encrypt(ctx, (const uint32 *) in, (uint32 *) out);
152 }
153 
154 static void
md_init(MD_CTX * ctx)155 md_init(MD_CTX * ctx)
156 {
157 	SHA256_Init(ctx);
158 }
159 
160 static void
md_update(MD_CTX * ctx,const uint8 * data,int len)161 md_update(MD_CTX * ctx, const uint8 *data, int len)
162 {
163 	SHA256_Update(ctx, data, len);
164 }
165 
166 static void
md_result(MD_CTX * ctx,uint8 * dst)167 md_result(MD_CTX * ctx, uint8 *dst)
168 {
169 	SHA256_CTX	tmp;
170 
171 	memcpy(&tmp, ctx, sizeof(*ctx));
172 	SHA256_Final(dst, &tmp);
173 	px_memset(&tmp, 0, sizeof(tmp));
174 }
175 
176 /*
177  * initialize state
178  */
179 static void
init_state(FState * st)180 init_state(FState *st)
181 {
182 	int			i;
183 
184 	memset(st, 0, sizeof(*st));
185 	for (i = 0; i < NUM_POOLS; i++)
186 		md_init(&st->pool[i]);
187 }
188 
189 /*
190  * Endianess does not matter.
191  * It just needs to change without repeating.
192  */
193 static void
inc_counter(FState * st)194 inc_counter(FState *st)
195 {
196 	uint32	   *val = (uint32 *) st->counter;
197 
198 	if (++val[0])
199 		return;
200 	if (++val[1])
201 		return;
202 	if (++val[2])
203 		return;
204 	++val[3];
205 }
206 
207 /*
208  * This is called 'cipher in counter mode'.
209  */
210 static void
encrypt_counter(FState * st,uint8 * dst)211 encrypt_counter(FState *st, uint8 *dst)
212 {
213 	ciph_encrypt(&st->ciph, st->counter, dst);
214 	inc_counter(st);
215 }
216 
217 
218 /*
219  * The time between reseed must be at least RESEED_INTERVAL
220  * microseconds.
221  */
222 static int
enough_time_passed(FState * st)223 enough_time_passed(FState *st)
224 {
225 	int			ok;
226 	struct timeval tv;
227 	struct timeval *last = &st->last_reseed_time;
228 
229 	gettimeofday(&tv, NULL);
230 
231 	/* check how much time has passed */
232 	ok = 0;
233 	if (tv.tv_sec > last->tv_sec + 1)
234 		ok = 1;
235 	else if (tv.tv_sec == last->tv_sec + 1)
236 	{
237 		if (1000000 + tv.tv_usec - last->tv_usec >= RESEED_INTERVAL)
238 			ok = 1;
239 	}
240 	else if (tv.tv_usec - last->tv_usec >= RESEED_INTERVAL)
241 		ok = 1;
242 
243 	/* reseed will happen, update last_reseed_time */
244 	if (ok)
245 		memcpy(last, &tv, sizeof(tv));
246 
247 	px_memset(&tv, 0, sizeof(tv));
248 
249 	return ok;
250 }
251 
252 /*
253  * generate new key from all the pools
254  */
255 static void
reseed(FState * st)256 reseed(FState *st)
257 {
258 	unsigned	k;
259 	unsigned	n;
260 	MD_CTX		key_md;
261 	uint8		buf[BLOCK];
262 
263 	/* set pool as empty */
264 	st->pool0_bytes = 0;
265 
266 	/*
267 	 * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
268 	 */
269 	n = ++st->reseed_count;
270 
271 	/*
272 	 * The goal: use k-th pool only 1/(2^k) of the time.
273 	 */
274 	md_init(&key_md);
275 	for (k = 0; k < NUM_POOLS; k++)
276 	{
277 		md_result(&st->pool[k], buf);
278 		md_update(&key_md, buf, BLOCK);
279 
280 		if (n & 1 || !n)
281 			break;
282 		n >>= 1;
283 	}
284 
285 	/* add old key into mix too */
286 	md_update(&key_md, st->key, BLOCK);
287 
288 	/* now we have new key */
289 	md_result(&key_md, st->key);
290 
291 	/* use new key */
292 	ciph_init(&st->ciph, st->key, BLOCK);
293 
294 	px_memset(&key_md, 0, sizeof(key_md));
295 	px_memset(buf, 0, BLOCK);
296 }
297 
298 /*
299  * Pick a random pool.  This uses key bytes as random source.
300  */
301 static unsigned
get_rand_pool(FState * st)302 get_rand_pool(FState *st)
303 {
304 	unsigned	rnd;
305 
306 	/*
307 	 * This slightly prefers lower pools - that is OK.
308 	 */
309 	rnd = st->key[st->rnd_pos] % NUM_POOLS;
310 
311 	st->rnd_pos++;
312 	if (st->rnd_pos >= BLOCK)
313 		st->rnd_pos = 0;
314 
315 	return rnd;
316 }
317 
318 /*
319  * update pools
320  */
321 static void
add_entropy(FState * st,const uint8 * data,unsigned len)322 add_entropy(FState *st, const uint8 *data, unsigned len)
323 {
324 	unsigned	pos;
325 	uint8		hash[BLOCK];
326 	MD_CTX		md;
327 
328 	/* hash given data */
329 	md_init(&md);
330 	md_update(&md, data, len);
331 	md_result(&md, hash);
332 
333 	/*
334 	 * Make sure the pool 0 is initialized, then update randomly.
335 	 */
336 	if (st->reseed_count == 0)
337 		pos = 0;
338 	else
339 		pos = get_rand_pool(st);
340 	md_update(&st->pool[pos], hash, BLOCK);
341 
342 	if (pos == 0)
343 		st->pool0_bytes += len;
344 
345 	px_memset(hash, 0, BLOCK);
346 	px_memset(&md, 0, sizeof(md));
347 }
348 
349 /*
350  * Just take 2 next blocks as new key
351  */
352 static void
rekey(FState * st)353 rekey(FState *st)
354 {
355 	encrypt_counter(st, st->key);
356 	encrypt_counter(st, st->key + CIPH_BLOCK);
357 	ciph_init(&st->ciph, st->key, BLOCK);
358 }
359 
360 /*
361  * Hide public constants. (counter, pools > 0)
362  *
363  * This can also be viewed as spreading the startup
364  * entropy over all of the components.
365  */
366 static void
startup_tricks(FState * st)367 startup_tricks(FState *st)
368 {
369 	int			i;
370 	uint8		buf[BLOCK];
371 
372 	/* Use next block as counter. */
373 	encrypt_counter(st, st->counter);
374 
375 	/* Now shuffle pools, excluding #0 */
376 	for (i = 1; i < NUM_POOLS; i++)
377 	{
378 		encrypt_counter(st, buf);
379 		encrypt_counter(st, buf + CIPH_BLOCK);
380 		md_update(&st->pool[i], buf, BLOCK);
381 	}
382 	px_memset(buf, 0, BLOCK);
383 
384 	/* Hide the key. */
385 	rekey(st);
386 
387 	/* This can be done only once. */
388 	st->tricks_done = 1;
389 }
390 
391 static void
extract_data(FState * st,unsigned count,uint8 * dst)392 extract_data(FState *st, unsigned count, uint8 *dst)
393 {
394 	unsigned	n;
395 	unsigned	block_nr = 0;
396 
397 	/* Should we reseed? */
398 	if (st->pool0_bytes >= POOL0_FILL || st->reseed_count == 0)
399 		if (enough_time_passed(st))
400 			reseed(st);
401 
402 	/* Do some randomization on first call */
403 	if (!st->tricks_done)
404 		startup_tricks(st);
405 
406 	while (count > 0)
407 	{
408 		/* produce bytes */
409 		encrypt_counter(st, st->result);
410 
411 		/* copy result */
412 		if (count > CIPH_BLOCK)
413 			n = CIPH_BLOCK;
414 		else
415 			n = count;
416 		memcpy(dst, st->result, n);
417 		dst += n;
418 		count -= n;
419 
420 		/* must not give out too many bytes with one key */
421 		block_nr++;
422 		if (block_nr > (RESEED_BYTES / CIPH_BLOCK))
423 		{
424 			rekey(st);
425 			block_nr = 0;
426 		}
427 	}
428 	/* Set new key for next request. */
429 	rekey(st);
430 }
431 
432 /*
433  * public interface
434  */
435 
436 static FState main_state;
437 static int	init_done = 0;
438 
439 void
fortuna_add_entropy(const uint8 * data,unsigned len)440 fortuna_add_entropy(const uint8 *data, unsigned len)
441 {
442 	if (!init_done)
443 	{
444 		init_state(&main_state);
445 		init_done = 1;
446 	}
447 	if (!data || !len)
448 		return;
449 	add_entropy(&main_state, data, len);
450 }
451 
452 void
fortuna_get_bytes(unsigned len,uint8 * dst)453 fortuna_get_bytes(unsigned len, uint8 *dst)
454 {
455 	if (!init_done)
456 	{
457 		init_state(&main_state);
458 		init_done = 1;
459 	}
460 	if (!dst || !len)
461 		return;
462 	extract_data(&main_state, len, dst);
463 }
464