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