1 /* $NetBSD: rand-fortuna.c,v 1.1.1.1 2011/04/13 18:14:50 elric Exp $ */
7 * Copyright (c) 2005 Marko Kreen
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * $PostgreSQL: pgsql/contrib/pgcrypto/fortuna.c,v 1.8 2006/10/04 00:29:46 momjian Exp $
39 #include <heim_threads.h>
42 #include <krb5/krb5-types.h>
44 #include <krb5/roken.h>
51 * Why Fortuna-like: There does not seem to be any definitive reference
52 * on Fortuna in the net. Instead this implementation is based on
53 * following references:
55 * http://en.wikipedia.org/wiki/Fortuna_(PRNG)
57 * http://jlcooke.ca/random/
58 * - Jean-Luc Cooke Fortuna-based /dev/random driver for Linux.
62 * There is some confusion about whether and how to carry forward
63 * the state of the pools. Seems like original Fortuna does not
64 * do it, resetting hash after each request. I guess expecting
65 * feeding to happen more often that requesting. This is absolutely
66 * unsuitable for pgcrypto, as nothing asynchronous happens here.
68 * J.L. Cooke fixed this by feeding previous hash to new re-initialized
71 * Fortuna predecessor Yarrow requires ability to query intermediate
72 * 'final result' from hash, without affecting it.
74 * This implementation uses the Yarrow method - asking intermediate
75 * results, but continuing with old state.
80 * Algorithm parameters
86 #define RESEED_INTERVAL 100000 /* 0.1 sec */
88 /* for one big request, reseed after this many bytes */
89 #define RESEED_BYTES (1024*1024)
92 * Skip reseed if pool 0 has less than this many
93 * bytes added since last reseed.
95 #define POOL0_FILL (256/8)
101 /* Both cipher key size and hash result size */
104 /* cipher block size */
105 #define CIPH_BLOCK 16
107 /* for internal wrappers */
108 #define MD_CTX SHA256_CTX
109 #define CIPH_CTX AES_KEY
113 unsigned char counter
[CIPH_BLOCK
];
114 unsigned char result
[CIPH_BLOCK
];
115 unsigned char key
[BLOCK
];
116 MD_CTX pool
[NUM_POOLS
];
118 unsigned reseed_count
;
119 struct timeval last_reseed_time
;
120 unsigned pool0_bytes
;
125 typedef struct fortuna_state FState
;
129 * Use our own wrappers here.
130 * - Need to get intermediate result from digest, without affecting it.
131 * - Need re-set key on a cipher context.
132 * - Algorithms are guaranteed to exist.
133 * - No memory allocations.
137 ciph_init(CIPH_CTX
* ctx
, const unsigned char *key
, int klen
)
139 AES_set_encrypt_key(key
, klen
* 8, ctx
);
143 ciph_encrypt(CIPH_CTX
* ctx
, const unsigned char *in
, unsigned char *out
)
145 AES_encrypt(in
, out
, ctx
);
149 md_init(MD_CTX
* ctx
)
155 md_update(MD_CTX
* ctx
, const unsigned char *data
, int len
)
157 SHA256_Update(ctx
, data
, len
);
161 md_result(MD_CTX
* ctx
, unsigned char *dst
)
165 memcpy(&tmp
, ctx
, sizeof(*ctx
));
166 SHA256_Final(dst
, &tmp
);
167 memset(&tmp
, 0, sizeof(tmp
));
174 init_state(FState
* st
)
178 memset(st
, 0, sizeof(*st
));
179 for (i
= 0; i
< NUM_POOLS
; i
++)
180 md_init(&st
->pool
[i
]);
185 * Endianess does not matter.
186 * It just needs to change without repeating.
189 inc_counter(FState
* st
)
191 uint32_t *val
= (uint32_t *) st
->counter
;
203 * This is called 'cipher in counter mode'.
206 encrypt_counter(FState
* st
, unsigned char *dst
)
208 ciph_encrypt(&st
->ciph
, st
->counter
, dst
);
214 * The time between reseed must be at least RESEED_INTERVAL
218 enough_time_passed(FState
* st
)
222 struct timeval
*last
= &st
->last_reseed_time
;
224 gettimeofday(&tv
, NULL
);
226 /* check how much time has passed */
228 if (tv
.tv_sec
> last
->tv_sec
+ 1)
230 else if (tv
.tv_sec
== last
->tv_sec
+ 1)
232 if (1000000 + tv
.tv_usec
- last
->tv_usec
>= RESEED_INTERVAL
)
235 else if (tv
.tv_usec
- last
->tv_usec
>= RESEED_INTERVAL
)
238 /* reseed will happen, update last_reseed_time */
240 memcpy(last
, &tv
, sizeof(tv
));
242 memset(&tv
, 0, sizeof(tv
));
248 * generate new key from all the pools
256 unsigned char buf
[BLOCK
];
258 /* set pool as empty */
262 * Both #0 and #1 reseed would use only pool 0. Just skip #0 then.
264 n
= ++st
->reseed_count
;
267 * The goal: use k-th pool only 1/(2^k) of the time.
270 for (k
= 0; k
< NUM_POOLS
; k
++)
272 md_result(&st
->pool
[k
], buf
);
273 md_update(&key_md
, buf
, BLOCK
);
280 /* add old key into mix too */
281 md_update(&key_md
, st
->key
, BLOCK
);
283 /* add pid to make output diverse after fork() */
284 md_update(&key_md
, (const unsigned char *)&st
->pid
, sizeof(st
->pid
));
286 /* now we have new key */
287 md_result(&key_md
, st
->key
);
290 ciph_init(&st
->ciph
, st
->key
, BLOCK
);
292 memset(&key_md
, 0, sizeof(key_md
));
293 memset(buf
, 0, BLOCK
);
297 * Pick a random pool. This uses key bytes as random source.
300 get_rand_pool(FState
* st
)
305 * This slightly prefers lower pools - thats OK.
307 rnd
= st
->key
[st
->rnd_pos
] % NUM_POOLS
;
310 if (st
->rnd_pos
>= BLOCK
)
320 add_entropy(FState
* st
, const unsigned char *data
, unsigned len
)
323 unsigned char hash
[BLOCK
];
326 /* hash given data */
328 md_update(&md
, data
, len
);
329 md_result(&md
, hash
);
332 * Make sure the pool 0 is initialized, then update randomly.
334 if (st
->reseed_count
== 0)
337 pos
= get_rand_pool(st
);
338 md_update(&st
->pool
[pos
], hash
, BLOCK
);
341 st
->pool0_bytes
+= len
;
343 memset(hash
, 0, BLOCK
);
344 memset(&md
, 0, sizeof(md
));
348 * Just take 2 next blocks as new key
353 encrypt_counter(st
, st
->key
);
354 encrypt_counter(st
, st
->key
+ CIPH_BLOCK
);
355 ciph_init(&st
->ciph
, st
->key
, BLOCK
);
359 * Hide public constants. (counter, pools > 0)
361 * This can also be viewed as spreading the startup
362 * entropy over all of the components.
365 startup_tricks(FState
* st
)
368 unsigned char buf
[BLOCK
];
370 /* Use next block as counter. */
371 encrypt_counter(st
, st
->counter
);
373 /* Now shuffle pools, excluding #0 */
374 for (i
= 1; i
< NUM_POOLS
; i
++)
376 encrypt_counter(st
, buf
);
377 encrypt_counter(st
, buf
+ CIPH_BLOCK
);
378 md_update(&st
->pool
[i
], buf
, BLOCK
);
380 memset(buf
, 0, BLOCK
);
385 /* This can be done only once. */
390 extract_data(FState
* st
, unsigned count
, unsigned char *dst
)
393 unsigned block_nr
= 0;
394 pid_t pid
= getpid();
396 /* Should we reseed? */
397 if (st
->pool0_bytes
>= POOL0_FILL
|| st
->reseed_count
== 0)
398 if (enough_time_passed(st
))
401 /* Do some randomization on first call */
402 if (!st
->tricks_done
)
405 /* If we forked, force a reseed again */
406 if (pid
!= st
->pid
) {
414 encrypt_counter(st
, st
->result
);
417 if (count
> CIPH_BLOCK
)
421 memcpy(dst
, st
->result
, n
);
425 /* must not give out too many bytes with one key */
427 if (block_nr
> (RESEED_BYTES
/ CIPH_BLOCK
))
433 /* Set new key for next request. */
441 static FState main_state
;
442 static int init_done
;
443 static int have_entropy
;
444 #define FORTUNA_RESEED_BYTE 10000
445 static unsigned resend_bytes
;
448 * This mutex protects all of the above static elements from concurrent
449 * access by multiple threads
451 static HEIMDAL_MUTEX fortuna_mutex
= HEIMDAL_MUTEX_INITIALIZER
;
454 * Try our best to do an inital seed
456 #define INIT_BYTES 128
459 * fortuna_mutex must be held across calls to this function
470 #ifndef NO_RAND_UNIX_METHOD
472 unsigned char buf
[INIT_BYTES
];
473 if ((*hc_rand_unix_method
.bytes
)(buf
, sizeof(buf
)) == 1) {
474 add_entropy(&main_state
, buf
, sizeof(buf
));
476 memset(buf
, 0, sizeof(buf
));
480 #ifdef HAVE_ARC4RANDOM
482 uint32_t buf
[INIT_BYTES
/ sizeof(uint32_t)];
485 for (i
= 0; i
< sizeof(buf
)/sizeof(buf
[0]); i
++)
486 buf
[i
] = arc4random();
487 add_entropy(&main_state
, (void *)buf
, sizeof(buf
));
491 #ifndef NO_RAND_EGD_METHOD
493 * Only to get egd entropy if /dev/random or arc4rand failed since
494 * it can be horribly slow to generate new bits.
497 unsigned char buf
[INIT_BYTES
];
498 if ((*hc_rand_egd_method
.bytes
)(buf
, sizeof(buf
)) == 1) {
499 add_entropy(&main_state
, buf
, sizeof(buf
));
501 memset(buf
, 0, sizeof(buf
));
506 * Fall back to gattering data from timer and secret files, this
507 * is really the last resort.
510 /* to save stackspace */
512 unsigned char buf
[INIT_BYTES
];
513 unsigned char shad
[1001];
518 if ((*hc_rand_timer_method
.bytes
)(u
.buf
, sizeof(u
.buf
)) == 1)
519 add_entropy(&main_state
, u
.buf
, sizeof(u
.buf
));
520 /* add /etc/shadow */
521 fd
= open("/etc/shadow", O_RDONLY
, 0);
525 /* add_entropy will hash the buf */
526 while ((n
= read(fd
, (char *)u
.shad
, sizeof(u
.shad
))) > 0)
527 add_entropy(&main_state
, u
.shad
, sizeof(u
.shad
));
531 memset(&u
, 0, sizeof(u
));
533 entropy_p
= 1; /* sure about this ? */
536 pid_t pid
= getpid();
537 add_entropy(&main_state
, (void *)&pid
, sizeof(pid
));
541 gettimeofday(&tv
, NULL
);
542 add_entropy(&main_state
, (void *)&tv
, sizeof(tv
));
547 add_entropy(&main_state
, (void *)&u
, sizeof(u
));
554 * fortuna_mutex must be held by callers of this function
561 init_state(&main_state
);
565 have_entropy
= fortuna_reseed();
566 return (init_done
&& have_entropy
);
572 fortuna_seed(const void *indata
, int size
)
574 HEIMDAL_MUTEX_lock(&fortuna_mutex
);
577 add_entropy(&main_state
, indata
, size
);
578 if (size
>= INIT_BYTES
)
581 HEIMDAL_MUTEX_unlock(&fortuna_mutex
);
585 fortuna_bytes(unsigned char *outdata
, int size
)
589 HEIMDAL_MUTEX_lock(&fortuna_mutex
);
594 resend_bytes
+= size
;
595 if (resend_bytes
> FORTUNA_RESEED_BYTE
|| resend_bytes
< size
) {
599 extract_data(&main_state
, size
, outdata
);
603 HEIMDAL_MUTEX_unlock(&fortuna_mutex
);
609 fortuna_cleanup(void)
611 HEIMDAL_MUTEX_lock(&fortuna_mutex
);
615 memset(&main_state
, 0, sizeof(main_state
));
617 HEIMDAL_MUTEX_unlock(&fortuna_mutex
);
621 fortuna_add(const void *indata
, int size
, double entropi
)
623 fortuna_seed(indata
, size
);
627 fortuna_pseudorand(unsigned char *outdata
, int size
)
629 return fortuna_bytes(outdata
, size
);
637 HEIMDAL_MUTEX_lock(&fortuna_mutex
);
638 result
= fortuna_init();
639 HEIMDAL_MUTEX_unlock(&fortuna_mutex
);
641 return result
? 1 : 0;
644 const RAND_METHOD hc_rand_fortuna_method
= {
654 RAND_fortuna_method(void)
656 return &hc_rand_fortuna_method
;