Start background writer during archive recovery. Background writer now performs
[PostgreSQL.git] / contrib / pgcrypto / fortuna.c
blobae4d04f3acdbdfa9b9812d05387783d3fcb2c1c7
1 /*
2 * fortuna.c
3 * Fortuna-like PRNG.
5 * Copyright (c) 2005 Marko Kreen
6 * All rights reserved.
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.
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.
29 * $PostgreSQL$
32 #include "postgres.h"
34 #include <sys/time.h>
35 #include <time.h>
37 #include "rijndael.h"
38 #include "sha2.h"
39 #include "fortuna.h"
43 * Why Fortuna-like: There does not seem to be any definitive reference
44 * on Fortuna in the net. Instead this implementation is based on
45 * following references:
47 * http://en.wikipedia.org/wiki/Fortuna_(PRNG)
48 * - Wikipedia article
49 * http://jlcooke.ca/random/
50 * - Jean-Luc Cooke Fortuna-based /dev/random driver for Linux.
54 * There is some confusion about whether and how to carry forward
55 * the state of the pools. Seems like original Fortuna does not
56 * do it, resetting hash after each request. I guess expecting
57 * feeding to happen more often that requesting. This is absolutely
58 * unsuitable for pgcrypto, as nothing asynchronous happens here.
60 * J.L. Cooke fixed this by feeding previous hash to new re-initialized
61 * hash context.
63 * Fortuna predecessor Yarrow requires ability to query intermediate
64 * 'final result' from hash, without affecting it.
66 * This implementation uses the Yarrow method - asking intermediate
67 * results, but continuing with old state.
72 * Algorithm parameters
76 * How many pools.
78 * Original Fortuna uses 32 pools, that means 32'th pool is
79 * used not earlier than in 13th year. This is a waste in
80 * pgcrypto, as we have very low-frequancy seeding. Here
81 * is preferable to have all entropy usable in reasonable time.
83 * With 23 pools, 23th pool is used after 9 days which seems
84 * more sane.
86 * In our case the minimal cycle time would be bit longer
87 * than the system-randomness feeding frequency.
89 #define NUM_POOLS 23
91 /* in microseconds */
92 #define RESEED_INTERVAL 100000 /* 0.1 sec */
94 /* for one big request, reseed after this many bytes */
95 #define RESEED_BYTES (1024*1024)
98 * Skip reseed if pool 0 has less than this many
99 * bytes added since last reseed.
101 #define POOL0_FILL (256/8)
104 * Algorithm constants
107 /* Both cipher key size and hash result size */
108 #define BLOCK 32
110 /* cipher block size */
111 #define CIPH_BLOCK 16
113 /* for internal wrappers */
114 #define MD_CTX SHA256_CTX
115 #define CIPH_CTX rijndael_ctx
117 struct fortuna_state
119 uint8 counter[CIPH_BLOCK];
120 uint8 result[CIPH_BLOCK];
121 uint8 key[BLOCK];
122 MD_CTX pool[NUM_POOLS];
123 CIPH_CTX ciph;
124 unsigned reseed_count;
125 struct timeval last_reseed_time;
126 unsigned pool0_bytes;
127 unsigned rnd_pos;
128 int tricks_done;
130 typedef struct fortuna_state FState;
134 * Use our own wrappers here.
135 * - Need to get intermediate result from digest, without affecting it.
136 * - Need re-set key on a cipher context.
137 * - Algorithms are guaranteed to exist.
138 * - No memory allocations.
141 static void
142 ciph_init(CIPH_CTX * ctx, const uint8 *key, int klen)
144 rijndael_set_key(ctx, (const uint32 *) key, klen, 1);
147 static void
148 ciph_encrypt(CIPH_CTX * ctx, const uint8 *in, uint8 *out)
150 rijndael_encrypt(ctx, (const uint32 *) in, (uint32 *) out);
153 static void
154 md_init(MD_CTX * ctx)
156 SHA256_Init(ctx);
159 static void
160 md_update(MD_CTX * ctx, const uint8 *data, int len)
162 SHA256_Update(ctx, data, len);
165 static void
166 md_result(MD_CTX * ctx, uint8 *dst)
168 SHA256_CTX tmp;
170 memcpy(&tmp, ctx, sizeof(*ctx));
171 SHA256_Final(dst, &tmp);
172 memset(&tmp, 0, sizeof(tmp));
176 * initialize state
178 static void
179 init_state(FState * st)
181 int i;
183 memset(st, 0, sizeof(*st));
184 for (i = 0; i < NUM_POOLS; i++)
185 md_init(&st->pool[i]);
189 * Endianess does not matter.
190 * It just needs to change without repeating.
192 static void
193 inc_counter(FState * st)
195 uint32 *val = (uint32 *) st->counter;
197 if (++val[0])
198 return;
199 if (++val[1])
200 return;
201 if (++val[2])
202 return;
203 ++val[3];
207 * This is called 'cipher in counter mode'.
209 static void
210 encrypt_counter(FState * st, uint8 *dst)
212 ciph_encrypt(&st->ciph, st->counter, dst);
213 inc_counter(st);
218 * The time between reseed must be at least RESEED_INTERVAL
219 * microseconds.
221 static int
222 enough_time_passed(FState * st)
224 int ok;
225 struct timeval tv;
226 struct timeval *last = &st->last_reseed_time;
228 gettimeofday(&tv, NULL);
230 /* check how much time has passed */
231 ok = 0;
232 if (tv.tv_sec > last->tv_sec + 1)
233 ok = 1;
234 else if (tv.tv_sec == last->tv_sec + 1)
236 if (1000000 + tv.tv_usec - last->tv_usec >= RESEED_INTERVAL)
237 ok = 1;
239 else if (tv.tv_usec - last->tv_usec >= RESEED_INTERVAL)
240 ok = 1;
242 /* reseed will happen, update last_reseed_time */
243 if (ok)
244 memcpy(last, &tv, sizeof(tv));
246 memset(&tv, 0, sizeof(tv));
248 return ok;
252 * generate new key from all the pools
254 static void
255 reseed(FState * st)
257 unsigned k;
258 unsigned n;
259 MD_CTX key_md;
260 uint8 buf[BLOCK];
262 /* set pool as empty */
263 st->pool0_bytes = 0;
266 * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
268 n = ++st->reseed_count;
271 * The goal: use k-th pool only 1/(2^k) of the time.
273 md_init(&key_md);
274 for (k = 0; k < NUM_POOLS; k++)
276 md_result(&st->pool[k], buf);
277 md_update(&key_md, buf, BLOCK);
279 if (n & 1 || !n)
280 break;
281 n >>= 1;
284 /* add old key into mix too */
285 md_update(&key_md, st->key, BLOCK);
287 /* now we have new key */
288 md_result(&key_md, st->key);
290 /* use new key */
291 ciph_init(&st->ciph, st->key, BLOCK);
293 memset(&key_md, 0, sizeof(key_md));
294 memset(buf, 0, BLOCK);
298 * Pick a random pool. This uses key bytes as random source.
300 static unsigned
301 get_rand_pool(FState * st)
303 unsigned rnd;
306 * This slightly prefers lower pools - thats OK.
308 rnd = st->key[st->rnd_pos] % NUM_POOLS;
310 st->rnd_pos++;
311 if (st->rnd_pos >= BLOCK)
312 st->rnd_pos = 0;
314 return rnd;
318 * update pools
320 static void
321 add_entropy(FState * st, const uint8 *data, unsigned len)
323 unsigned pos;
324 uint8 hash[BLOCK];
325 MD_CTX md;
327 /* hash given data */
328 md_init(&md);
329 md_update(&md, data, len);
330 md_result(&md, hash);
333 * Make sure the pool 0 is initialized, then update randomly.
335 if (st->reseed_count == 0)
336 pos = 0;
337 else
338 pos = get_rand_pool(st);
339 md_update(&st->pool[pos], hash, BLOCK);
341 if (pos == 0)
342 st->pool0_bytes += len;
344 memset(hash, 0, BLOCK);
345 memset(&md, 0, sizeof(md));
349 * Just take 2 next blocks as new key
351 static void
352 rekey(FState * st)
354 encrypt_counter(st, st->key);
355 encrypt_counter(st, st->key + CIPH_BLOCK);
356 ciph_init(&st->ciph, st->key, BLOCK);
360 * Hide public constants. (counter, pools > 0)
362 * This can also be viewed as spreading the startup
363 * entropy over all of the components.
365 static void
366 startup_tricks(FState * st)
368 int i;
369 uint8 buf[BLOCK];
371 /* Use next block as counter. */
372 encrypt_counter(st, st->counter);
374 /* Now shuffle pools, excluding #0 */
375 for (i = 1; i < NUM_POOLS; i++)
377 encrypt_counter(st, buf);
378 encrypt_counter(st, buf + CIPH_BLOCK);
379 md_update(&st->pool[i], buf, BLOCK);
381 memset(buf, 0, BLOCK);
383 /* Hide the key. */
384 rekey(st);
386 /* This can be done only once. */
387 st->tricks_done = 1;
390 static void
391 extract_data(FState * st, unsigned count, uint8 *dst)
393 unsigned n;
394 unsigned block_nr = 0;
396 /* Should we reseed? */
397 if (st->pool0_bytes >= POOL0_FILL || st->reseed_count == 0)
398 if (enough_time_passed(st))
399 reseed(st);
401 /* Do some randomization on first call */
402 if (!st->tricks_done)
403 startup_tricks(st);
405 while (count > 0)
407 /* produce bytes */
408 encrypt_counter(st, st->result);
410 /* copy result */
411 if (count > CIPH_BLOCK)
412 n = CIPH_BLOCK;
413 else
414 n = count;
415 memcpy(dst, st->result, n);
416 dst += n;
417 count -= n;
419 /* must not give out too many bytes with one key */
420 block_nr++;
421 if (block_nr > (RESEED_BYTES / CIPH_BLOCK))
423 rekey(st);
424 block_nr = 0;
427 /* Set new key for next request. */
428 rekey(st);
432 * public interface
435 static FState main_state;
436 static int init_done = 0;
438 void
439 fortuna_add_entropy(const uint8 *data, unsigned len)
441 if (!init_done)
443 init_state(&main_state);
444 init_done = 1;
446 if (!data || !len)
447 return;
448 add_entropy(&main_state, data, len);
451 void
452 fortuna_get_bytes(unsigned len, uint8 *dst)
454 if (!init_done)
456 init_state(&main_state);
457 init_done = 1;
459 if (!dst || !len)
460 return;
461 extract_data(&main_state, len, dst);