3 * Secure random number generator
5 * (c) 1998 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- Header files ------------------------------------------------------*/
36 #include <mLib/bits.h>
48 #include "twofish-counter.h"
51 #define CIPHER_CTX twofish_counterctx
52 #define CIPHER_INIT twofish_counterinit
53 #define CIPHER_ENCRYPT twofish_counterencrypt
54 #define CIPHER_IVSZ TWOFISH_BLKSZ
55 #define CIPHER_KEYSZ TWOFISH_KEYSZ
57 #define HASH_CTX sha256_ctx
58 #define HASH_INIT sha256_init
59 #define HASH sha256_hash
60 #define HASH_DONE sha256_done
61 #define HASH_SZ SHA256_HASHSZ
63 /*----- Static variables --------------------------------------------------*/
65 static const grand_ops gops;
67 typedef struct rand__gctx {
76 { "Catacomb global random byte pool" },
80 /*----- Macros ------------------------------------------------------------*/
82 #define RAND_RESOLVE(r) \
83 do { if ((r) == RAND_GLOBAL) r = &rand_global.p; } while (0)
85 #define GENCHECK(r) do { \
86 unsigned gen = rand_generation(); \
87 if (r->gen != gen) { r->gen = gen; rand_gate(r); } \
90 static int quick(rand_pool *);
91 #define QUICK(r) do { \
93 if ((r)->s && (r)->s->timer) (r)->s->timer(r); \
96 /*----- Main code ---------------------------------------------------------*/
98 /* --- @rand_init@ --- *
100 * Arguments: @rand_pool *r@ = pointer to a randomness pool
104 * Use: Initializes a randomness pool. The pool doesn't start out
105 * very random: that's your job to sort out. A good suggestion
106 * would be to attach an appropriate noise source and call
110 void rand_init(rand_pool *r)
113 memset(r->pool, 0, sizeof(r->pool));
114 memset(r->buf, 0, sizeof(r->buf));
115 r->gen = rand_generation();
118 r->ibits = r->obits = 0;
120 r->s = &noise_source;
125 /* --- @rand_noisesrc@ --- *
127 * Arguments: @rand_pool *r@ = pointer to a randomness pool
128 * @const rand_source *s@ = pointer to source definition
132 * Use: Sets a noise source for a randomness pool. When the pool's
133 * estimate of good random bits falls to zero, the @getnoise@
134 * function is called, passing the pool handle as an argument.
135 * It is expected to increase the number of good bits by at
136 * least one, because it'll be called over and over again until
137 * there are enough bits to satisfy the caller. The @timer@
138 * function is called frequently throughout the generator's
142 void rand_noisesrc(rand_pool *r, const rand_source *s)
148 /* --- @rand_quick@ --- *
150 * Arguments: @rand_pool *r@ = pointer to a randomness pool
152 * Returns: Zero on success; @-1@ on failure.
154 * Use Attempts to use some machine-specific `quick' source of
155 * entropy to top up @r@. This may not do anything at all on
159 CPU_DISPATCH(static, return, int, quick, (rand_pool *r), (r),
160 pick_quick, trivial_quick);
162 static int trivial_quick(rand_pool *r) { return (-1); }
164 #if __GNUC__ && (CPUFAM_X86 || CPUFAM_AMD64)
165 static int rdrand_quick(rand_pool *r)
170 __asm__ ("0: rdrand %0; jc 9f; dec %1; jnz 0b; 9:"
171 : "=r" (rr), "=r" (i) : "1" (i) : "cc");
173 rand_add(r, &rr, sizeof(rr), 8*sizeof(rr));
178 static quick__functype *pick_quick(void)
180 #if __GNUC__ && (CPUFAM_X86 || CPUFAM_AMD64)
181 DISPATCH_PICK_COND(rand_quick, rdrand_quick,
182 cpu_feature_p(CPUFEAT_X86_RDRAND));
184 DISPATCH_PICK_FALLBACK(rand_quick, trivial_quick);
187 int rand_quick(rand_pool *r) { RAND_RESOLVE(r); return (quick(r)); }
189 /* --- @rand_seed@ --- *
191 * Arguments: @rand_pool *r@ = pointer to a randomness pool
192 * @unsigned bits@ = number of bits to ensure
196 * Use: Ensures that there are at least @bits@ good bits of entropy
197 * in the pool. It is recommended that you call this after
198 * initializing a new pool. Requesting @bits > RAND_IBITS@ is
199 * doomed to failure (and is an error).
202 void rand_seed(rand_pool *r, unsigned bits)
206 assert(((void)"bits pointlessly large in rand_seed", bits <= RAND_IBITS));
207 assert(((void)"no noise source in rand_seed", r->s));
209 while (r->ibits < bits)
214 /* --- @rand_key@ --- *
216 * Arguments: @rand_pool *r@ = pointer to a randomness pool
217 * @const void *k@ = pointer to key data
218 * @size_t sz@ = size of key data
222 * Use: Sets the secret key for a randomness pool. The key is used
223 * when mixing in new random bits.
226 void rand_key(rand_pool *r, const void *k, size_t sz)
230 static const char label[] = "Catacomb random pool key";
234 assert(HASH_SZ >= RAND_KEYSZ);
236 HASH(&hc, label, sizeof(label));
237 if (sz) HASH(&hc, k, sz);
239 memcpy(r->k.k, h, RAND_KEYSZ);
242 /* --- @rand_add@ --- *
244 * Arguments: @rand_pool *r@ = pointer to a randomness pool
245 * @const void *p@ = pointer a buffer of data to add
246 * @size_t sz@ = size of the data buffer
247 * @unsigned goodbits@ = number of good bits estimated in buffer
251 * Use: Mixes the data in the buffer with the contents of the
252 * pool. The estimate of the number of good bits is added to
253 * the pool's own count. The mixing operation is not
254 * cryptographically strong. However, data in the input pool
255 * isn't output directly, only through the one-way gating
256 * operation, so that shouldn't matter.
259 void rand_add(rand_pool *r, const void *p, size_t sz, unsigned goodbits)
264 #if RAND_POOLSZ != 128
265 # error Polynomial in rand_add is out of date. Fix it.
270 i = r->i; rot = r->irot;
274 r->pool[i] ^= (ROL8(o, rot) ^
275 r->pool[(i + 1) % RAND_POOLSZ] ^
276 r->pool[(i + 2) % RAND_POOLSZ] ^
277 r->pool[(i + 7) % RAND_POOLSZ]);
279 i++; if (i >= RAND_POOLSZ) i -= RAND_POOLSZ;
285 r->ibits += goodbits;
286 if (r->ibits > RAND_IBITS)
287 r->ibits = RAND_IBITS;
290 /* --- @rand_goodbits@ --- *
292 * Arguments: @rand_pool *r@ = pointer to a randomness pool
294 * Returns: Estimate of the number of good bits remaining in the pool.
297 unsigned rand_goodbits(rand_pool *r)
300 return (r->ibits + r->obits);
303 /* --- @rand_gate@ --- *
305 * Arguments: @rand_pool *r@ = pointer to a randomness pool
309 * Use: Mixes up the entire state of the generator in a nonreversible
313 void rand_gate(rand_pool *r)
315 octet h[HASH_SZ], g[4];
322 /* --- Hash up all the data in the pool --- */
325 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
326 HASH(&hc, r->k.k, RAND_KEYSZ);
327 HASH(&hc, r->pool, RAND_POOLSZ);
328 HASH(&hc, r->buf, RAND_BUFSZ);
332 /* --- Now mangle all of the data based on the hash --- */
334 assert(CIPHER_KEYSZ <= HASH_SZ);
335 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
336 CIPHER_ENCRYPT(&cc, r->pool, r->pool, RAND_POOLSZ);
337 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
340 /* --- Reset the various state variables --- */
343 r->obits += r->ibits;
344 if (r->obits > RAND_OBITS) {
345 r->ibits = r->obits - r->ibits;
346 r->obits = RAND_OBITS;
352 /* --- @rand_stretch@ --- *
354 * Arguments: @rand_pool *r@ = pointer to a randomness pool
358 * Use: Stretches the contents of the output buffer by transforming
359 * it in a nonreversible way. This doesn't add any entropy
360 * worth speaking about, but it works well enough when the
361 * caller doesn't care about that sort of thing.
364 void rand_stretch(rand_pool *r)
366 octet h[HASH_SZ], g[4];
373 /* --- Hash up all the data in the buffer --- */
376 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
377 HASH(&hc, r->k.k, RAND_KEYSZ);
378 HASH(&hc, r->pool, RAND_POOLSZ);
379 HASH(&hc, r->buf, RAND_BUFSZ);
383 /* --- Now mangle the buffer based on the hash --- */
385 assert(CIPHER_KEYSZ <= HASH_SZ);
386 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
387 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
390 /* --- Reset the various state variables --- */
396 /* --- @rand_get@ --- *
398 * Arguments: @rand_pool *r@ = pointer to a randomness pool
399 * @void *p@ = pointer to output buffer
400 * @size_t sz@ = size of output buffer
404 * Use: Gets random data from the pool. The pool's contents can't be
405 * determined from the output of this function; nor can the
406 * output data be determined from a knowledge of the data input
407 * to the pool wihtout also having knowledge of the secret key.
408 * The good bits counter is decremented, although no special
409 * action is taken if it reaches zero.
412 void rand_get(rand_pool *r, void *p, size_t sz)
423 if (r->o + sz <= RAND_BUFSZ) {
424 memcpy(o, r->buf + r->o, sz);
428 size_t chunk = RAND_BUFSZ - r->o;
430 memcpy(o, r->buf + r->o, chunk);
438 if (r->obits > sz * 8)
444 /* --- @rand_getgood@ --- *
446 * Arguments: @rand_pool *r@ = pointer to a randomness pool
447 * @void *p@ = pointer to output buffer
448 * @size_t sz@ = size of output buffer
452 * Use: Gets random data from the pool, ensuring that there are
453 * enough good bits. This interface isn't recommended: it makes
454 * the generator slow, and doesn't provide much more security
455 * than @rand_get@, assuming you've previously done a
459 void rand_getgood(rand_pool *r, void *p, size_t sz)
467 if (!r->s || !r->s->getnoise) {
477 if (chunk * 8 > r->obits) {
478 if (chunk * 8 > r->ibits + r->obits)
479 do r->s->getnoise(r); while (r->ibits + r->obits < 256);
481 if (chunk * 8 > r->obits)
482 chunk = r->obits / 8;
485 if (chunk + r->o > RAND_BUFSZ)
486 chunk = RAND_BUFSZ - r->o;
488 memcpy(o, r->buf + r->o, chunk);
490 r->obits -= chunk * 8;
496 /*----- Generic random number generator interface -------------------------*/
498 static void gdestroy(grand *r)
501 if (g != &rand_global) {
507 static int gmisc(grand *r, unsigned op, ...)
516 switch (va_arg(ap, unsigned)) {
519 case GRAND_SEEDUINT32:
520 case GRAND_SEEDBLOCK:
537 case GRAND_SEEDINT: {
538 unsigned u = va_arg(ap, unsigned);
539 rand_add(&g->p, &u, sizeof(u), sizeof(u));
541 case GRAND_SEEDUINT32: {
542 uint32 i = va_arg(ap, uint32);
543 rand_add(&g->p, &i, sizeof(i), 4);
545 case GRAND_SEEDBLOCK: {
546 const void *p = va_arg(ap, const void *);
547 size_t sz = va_arg(ap, size_t);
548 rand_add(&g->p, p, sz, sz);
550 case GRAND_SEEDRAND: {
551 grand *rr = va_arg(ap, grand *);
553 rr->ops->fill(rr, buf, sizeof(buf));
554 rand_add(&g->p, buf, sizeof(buf), 8);
563 const void *k = va_arg(ap, const void *);
564 size_t sz = va_arg(ap, size_t);
565 rand_key(&g->p, k, sz);
568 rand_noisesrc(&g->p, va_arg(ap, const rand_source *));
571 rand_seed(&g->p, va_arg(ap, unsigned));
577 rc = rand_goodbits(&g->p);
580 const void *p = va_arg(ap, const void *);
581 size_t sz = va_arg(ap, size_t);
582 unsigned goodbits = va_arg(ap, unsigned);
583 rand_add(&g->p, p, sz, goodbits);
594 static octet gbyte(grand *r)
598 rand_getgood(&g->p, &o, 1);
602 static uint32 gword(grand *r)
606 rand_getgood(&g->p, &b, sizeof(b));
610 static void gfill(grand *r, void *p, size_t sz)
613 rand_get(&g->p, p, sz);
616 static const grand_ops gops = {
620 gword, gbyte, gword, grand_defaultrange, gfill
623 /* --- @rand_create@ --- *
627 * Returns: Pointer to a generic generator.
629 * Use: Constructs a generic generator interface over a Catacomb
630 * entropy pool generator.
633 grand *rand_create(void)
635 gctx *g = S_CREATE(gctx);
641 /*----- That's all, folks -------------------------------------------------*/