304c68dccafe4e7e130ba91faa279c45733a5c57
[catacomb] / rand / rand.c
1 /* -*-c-*-
2 *
3 * Secure random number generator
4 *
5 * (c) 1998 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Catacomb.
11 *
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.
16 *
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.
21 *
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,
25 * MA 02111-1307, USA.
26 */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include "config.h"
31
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35
36 #include <mLib/bits.h>
37 #include <mLib/sub.h>
38
39 #include "arena.h"
40 #include "dispatch.h"
41 #include "paranoia.h"
42
43 #define RAND__HACKS
44 #include "rand.h"
45
46 #include "noise.h"
47
48 #include "twofish-counter.h"
49 #include "sha256.h"
50
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
56
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
62
63 /*----- Static variables --------------------------------------------------*/
64
65 static const grand_ops gops;
66
67 typedef struct rand__gctx {
68 grand r;
69 rand_pool p;
70 } gctx;
71
72 gctx rand_global = {
73 { &gops },
74 { { 0 }, 0, 0, 0, 0,
75 { 0 }, RAND_SECSZ, 0,
76 { "Catacomb global random byte pool" },
77 &noise_source }
78 };
79
80 /*----- Macros ------------------------------------------------------------*/
81
82 #define RAND_RESOLVE(r) \
83 do { if ((r) == RAND_GLOBAL) r = &rand_global.p; } while (0)
84
85 #define GENCHECK(r) do { \
86 unsigned gen = rand_generation(); \
87 if (r->gen != gen) { r->gen = gen; rand_gate(r); } \
88 } while (0)
89
90 static int quick(rand_pool *);
91 #define QUICK(r) do { \
92 quick(r); \
93 if ((r)->s && (r)->s->timer) (r)->s->timer(r); \
94 } while (0)
95
96 /*----- Main code ---------------------------------------------------------*/
97
98 /* --- @rand_init@ --- *
99 *
100 * Arguments: @rand_pool *r@ = pointer to a randomness pool
101 *
102 * Returns: ---
103 *
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
107 * @rand_seed@.
108 */
109
110 void rand_init(rand_pool *r)
111 {
112 RAND_RESOLVE(r);
113 memset(r->pool, 0, sizeof(r->pool));
114 memset(r->buf, 0, sizeof(r->buf));
115 r->gen = rand_generation();
116 r->i = 0;
117 r->irot = 0;
118 r->ibits = r->obits = 0;
119 r->o = RAND_SECSZ;
120 r->s = &noise_source;
121 rand_key(r, 0, 0);
122 rand_gate(r);
123 }
124
125 /* --- @rand_noisesrc@ --- *
126 *
127 * Arguments: @rand_pool *r@ = pointer to a randomness pool
128 * @const rand_source *s@ = pointer to source definition
129 *
130 * Returns: ---
131 *
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
139 * operation.
140 */
141
142 void rand_noisesrc(rand_pool *r, const rand_source *s)
143 {
144 RAND_RESOLVE(r);
145 r->s = s;
146 }
147
148 /* --- @rand_quick@ --- *
149 *
150 * Arguments: @rand_pool *r@ = pointer to a randomness pool
151 *
152 * Returns: Zero on success; @-1@ on failure.
153 *
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
156 * many systems.
157 */
158
159 CPU_DISPATCH(static, return, int, quick, (rand_pool *r), (r),
160 pick_quick, trivial_quick);
161
162 static int trivial_quick(rand_pool *r) { return (-1); }
163
164 #if CPUFAM_X86 || CPUFAM_AMD64
165 extern int rand_quick_x86ish_rdrand(rand_pool */*r*/);
166 #endif
167
168 static quick__functype *pick_quick(void)
169 {
170 #if CPUFAM_X86 || CPUFAM_AMD64
171 DISPATCH_PICK_COND(rand_quick, rand_quick_x86ish_rdrand,
172 cpu_feature_p(CPUFEAT_X86_RDRAND));
173 #endif
174 DISPATCH_PICK_FALLBACK(rand_quick, trivial_quick);
175 }
176
177 int rand_quick(rand_pool *r) { RAND_RESOLVE(r); return (quick(r)); }
178
179 /* --- @rand_seed@ --- *
180 *
181 * Arguments: @rand_pool *r@ = pointer to a randomness pool
182 * @unsigned bits@ = number of bits to ensure
183 *
184 * Returns: ---
185 *
186 * Use: Ensures that there are at least @bits@ good bits of entropy
187 * in the pool. It is recommended that you call this after
188 * initializing a new pool. Requesting @bits > RAND_IBITS@ is
189 * doomed to failure (and is an error).
190 */
191
192 void rand_seed(rand_pool *r, unsigned bits)
193 {
194 RAND_RESOLVE(r);
195
196 assert(((void)"bits pointlessly large in rand_seed", bits <= RAND_IBITS));
197 assert(((void)"no noise source in rand_seed", r->s));
198
199 while (r->ibits < bits)
200 r->s->getnoise(r);
201 rand_gate(r);
202 }
203
204 /* --- @rand_key@ --- *
205 *
206 * Arguments: @rand_pool *r@ = pointer to a randomness pool
207 * @const void *k@ = pointer to key data
208 * @size_t sz@ = size of key data
209 *
210 * Returns: ---
211 *
212 * Use: Sets the secret key for a randomness pool. The key is used
213 * when mixing in new random bits.
214 */
215
216 void rand_key(rand_pool *r, const void *k, size_t sz)
217 {
218 HASH_CTX hc;
219 octet h[HASH_SZ];
220 static const char label[] = "Catacomb random pool key";
221
222 RAND_RESOLVE(r);
223
224 assert(HASH_SZ >= RAND_KEYSZ);
225 HASH_INIT(&hc);
226 HASH(&hc, label, sizeof(label));
227 if (sz) HASH(&hc, k, sz);
228 HASH_DONE(&hc, h);
229 memcpy(r->k.k, h, RAND_KEYSZ);
230 }
231
232 /* --- @rand_add@ --- *
233 *
234 * Arguments: @rand_pool *r@ = pointer to a randomness pool
235 * @const void *p@ = pointer a buffer of data to add
236 * @size_t sz@ = size of the data buffer
237 * @unsigned goodbits@ = number of good bits estimated in buffer
238 *
239 * Returns: ---
240 *
241 * Use: Mixes the data in the buffer with the contents of the
242 * pool. The estimate of the number of good bits is added to
243 * the pool's own count. The mixing operation is not
244 * cryptographically strong. However, data in the input pool
245 * isn't output directly, only through the one-way gating
246 * operation, so that shouldn't matter.
247 */
248
249 void rand_add(rand_pool *r, const void *p, size_t sz, unsigned goodbits)
250 {
251 const octet *c = p;
252 int i, rot;
253
254 STATIC_ASSERT(RAND_POOLSZ == 128, "Polynomial doesn't match pool size");
255
256 RAND_RESOLVE(r);
257
258 i = r->i; rot = r->irot;
259
260 while (sz) {
261 octet o = *c++;
262 r->pool[i] ^= (ROL8(o, rot) ^
263 r->pool[(i + 1) % RAND_POOLSZ] ^
264 r->pool[(i + 2) % RAND_POOLSZ] ^
265 r->pool[(i + 7) % RAND_POOLSZ]);
266 rot = (rot + 5) & 7;
267 i++; if (i >= RAND_POOLSZ) i -= RAND_POOLSZ;
268 sz--;
269 }
270
271 r->i = i;
272 r->irot = rot;
273 r->ibits += goodbits;
274 if (r->ibits > RAND_IBITS)
275 r->ibits = RAND_IBITS;
276 }
277
278 /* --- @rand_goodbits@ --- *
279 *
280 * Arguments: @rand_pool *r@ = pointer to a randomness pool
281 *
282 * Returns: Estimate of the number of good bits remaining in the pool.
283 */
284
285 unsigned rand_goodbits(rand_pool *r)
286 {
287 RAND_RESOLVE(r);
288 return (r->ibits + r->obits);
289 }
290
291 /* --- @rand_gate@ --- *
292 *
293 * Arguments: @rand_pool *r@ = pointer to a randomness pool
294 *
295 * Returns: ---
296 *
297 * Use: Mixes up the entire state of the generator in a nonreversible
298 * way.
299 */
300
301 void rand_gate(rand_pool *r)
302 {
303 octet h[HASH_SZ], g[4];
304 HASH_CTX hc;
305 CIPHER_CTX cc;
306
307 STATIC_ASSERT(CIPHER_KEYSZ <= HASH_SZ, "rand cipher keysize too long");
308
309 RAND_RESOLVE(r);
310 QUICK(r);
311
312 /* --- Hash up all the data in the pool --- */
313
314 HASH_INIT(&hc);
315 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
316 HASH(&hc, r->k.k, RAND_KEYSZ);
317 HASH(&hc, r->pool, RAND_POOLSZ);
318 HASH(&hc, r->buf, RAND_BUFSZ);
319 HASH_DONE(&hc, h);
320 BURN(hc);
321
322 /* --- Now mangle all of the data based on the hash --- */
323
324 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
325 CIPHER_ENCRYPT(&cc, r->pool, r->pool, RAND_POOLSZ);
326 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
327 BURN(cc);
328
329 /* --- Reset the various state variables --- */
330
331 r->o = RAND_SECSZ;
332 r->obits += r->ibits;
333 if (r->obits > RAND_OBITS) {
334 r->ibits = r->obits - r->ibits;
335 r->obits = RAND_OBITS;
336 } else
337 r->ibits = 0;
338 QUICK(r);
339 }
340
341 /* --- @rand_stretch@ --- *
342 *
343 * Arguments: @rand_pool *r@ = pointer to a randomness pool
344 *
345 * Returns: ---
346 *
347 * Use: Stretches the contents of the output buffer by transforming
348 * it in a nonreversible way. This doesn't add any entropy
349 * worth speaking about, but it works well enough when the
350 * caller doesn't care about that sort of thing.
351 */
352
353 void rand_stretch(rand_pool *r)
354 {
355 octet h[HASH_SZ], g[4];
356 HASH_CTX hc;
357 CIPHER_CTX cc;
358
359 STATIC_ASSERT(CIPHER_KEYSZ <= HASH_SZ, "rand cipher keysize too long");
360
361 RAND_RESOLVE(r);
362 QUICK(r);
363
364 /* --- Hash up all the data in the buffer --- */
365
366 HASH_INIT(&hc);
367 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
368 HASH(&hc, r->k.k, RAND_KEYSZ);
369 HASH(&hc, r->pool, RAND_POOLSZ);
370 HASH(&hc, r->buf, RAND_BUFSZ);
371 HASH_DONE(&hc, h);
372 BURN(hc);
373
374 /* --- Now mangle the buffer based on the hash --- */
375
376 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
377 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
378 BURN(cc);
379
380 /* --- Reset the various state variables --- */
381
382 r->o = RAND_SECSZ;
383 QUICK(r);
384 }
385
386 /* --- @rand_get@ --- *
387 *
388 * Arguments: @rand_pool *r@ = pointer to a randomness pool
389 * @void *p@ = pointer to output buffer
390 * @size_t sz@ = size of output buffer
391 *
392 * Returns: ---
393 *
394 * Use: Gets random data from the pool. The pool's contents can't be
395 * determined from the output of this function; nor can the
396 * output data be determined from a knowledge of the data input
397 * to the pool wihtout also having knowledge of the secret key.
398 * The good bits counter is decremented, although no special
399 * action is taken if it reaches zero.
400 */
401
402 void rand_get(rand_pool *r, void *p, size_t sz)
403 {
404 octet *o = p;
405
406 RAND_RESOLVE(r);
407 GENCHECK(r);
408 QUICK(r);
409
410 if (!sz)
411 return;
412 for (;;) {
413 if (r->o + sz <= RAND_BUFSZ) {
414 memcpy(o, r->buf + r->o, sz);
415 r->o += sz;
416 break;
417 } else {
418 size_t chunk = RAND_BUFSZ - r->o;
419 if (chunk) {
420 memcpy(o, r->buf + r->o, chunk);
421 sz -= chunk;
422 o += chunk;
423 }
424 rand_stretch(r);
425 }
426 }
427
428 if (r->obits > sz * 8)
429 r->obits -= sz * 8;
430 else
431 r->obits = 0;
432 }
433
434 /* --- @rand_getgood@ --- *
435 *
436 * Arguments: @rand_pool *r@ = pointer to a randomness pool
437 * @void *p@ = pointer to output buffer
438 * @size_t sz@ = size of output buffer
439 *
440 * Returns: ---
441 *
442 * Use: Gets random data from the pool, ensuring that there are
443 * enough good bits. This interface isn't recommended: it makes
444 * the generator slow, and doesn't provide much more security
445 * than @rand_get@, assuming you've previously done a
446 * @rand_seed@.
447 */
448
449 void rand_getgood(rand_pool *r, void *p, size_t sz)
450 {
451 octet *o = p;
452
453 RAND_RESOLVE(r);
454
455 if (!sz)
456 return;
457 if (!r->s || !r->s->getnoise) {
458 rand_get(r, p, sz);
459 return;
460 }
461 GENCHECK(r);
462 QUICK(r);
463
464 while (sz) {
465 size_t chunk = sz;
466
467 if (chunk * 8 > r->obits) {
468 if (chunk * 8 > r->ibits + r->obits)
469 do r->s->getnoise(r); while (r->ibits + r->obits < 256);
470 rand_gate(r);
471 if (chunk * 8 > r->obits)
472 chunk = r->obits / 8;
473 }
474
475 if (chunk + r->o > RAND_BUFSZ)
476 chunk = RAND_BUFSZ - r->o;
477
478 memcpy(o, r->buf + r->o, chunk);
479 r->o += chunk;
480 r->obits -= chunk * 8;
481 o += chunk;
482 sz -= chunk;
483 }
484 }
485
486 /*----- Generic random number generator interface -------------------------*/
487
488 static void gdestroy(grand *r)
489 {
490 gctx *g = (gctx *)r;
491 if (g != &rand_global) {
492 BURN(*g);
493 S_DESTROY(g);
494 }
495 }
496
497 static int gmisc(grand *r, unsigned op, ...)
498 {
499 gctx *g = (gctx *)r;
500 va_list ap;
501 int rc = 0;
502 va_start(ap, op);
503
504 switch (op) {
505 case GRAND_CHECK:
506 switch (va_arg(ap, unsigned)) {
507 case GRAND_CHECK:
508 case GRAND_SEEDINT:
509 case GRAND_SEEDUINT32:
510 case GRAND_SEEDBLOCK:
511 case GRAND_SEEDRAND:
512 case RAND_GATE:
513 case RAND_STRETCH:
514 case RAND_KEY:
515 case RAND_NOISESRC:
516 case RAND_SEED:
517 case RAND_TIMER:
518 case RAND_GOODBITS:
519 case RAND_ADD:
520 rc = 1;
521 break;
522 default:
523 rc = 0;
524 break;
525 }
526 break;
527 case GRAND_SEEDINT: {
528 unsigned u = va_arg(ap, unsigned);
529 rand_add(&g->p, &u, sizeof(u), sizeof(u));
530 } break;
531 case GRAND_SEEDUINT32: {
532 uint32 i = va_arg(ap, uint32);
533 rand_add(&g->p, &i, sizeof(i), 4);
534 } break;
535 case GRAND_SEEDBLOCK: {
536 const void *p = va_arg(ap, const void *);
537 size_t sz = va_arg(ap, size_t);
538 rand_add(&g->p, p, sz, sz);
539 } break;
540 case GRAND_SEEDRAND: {
541 grand *rr = va_arg(ap, grand *);
542 octet buf[16];
543 rr->ops->fill(rr, buf, sizeof(buf));
544 rand_add(&g->p, buf, sizeof(buf), 8);
545 } break;
546 case RAND_GATE:
547 rand_gate(&g->p);
548 break;
549 case RAND_STRETCH:
550 rand_stretch(&g->p);
551 break;
552 case RAND_KEY: {
553 const void *k = va_arg(ap, const void *);
554 size_t sz = va_arg(ap, size_t);
555 rand_key(&g->p, k, sz);
556 } break;
557 case RAND_NOISESRC:
558 rand_noisesrc(&g->p, va_arg(ap, const rand_source *));
559 break;
560 case RAND_SEED:
561 rand_seed(&g->p, va_arg(ap, unsigned));
562 break;
563 case RAND_TIMER:
564 QUICK(&g->p);
565 break;
566 case RAND_GOODBITS:
567 rc = rand_goodbits(&g->p);
568 break;
569 case RAND_ADD: {
570 const void *p = va_arg(ap, const void *);
571 size_t sz = va_arg(ap, size_t);
572 unsigned goodbits = va_arg(ap, unsigned);
573 rand_add(&g->p, p, sz, goodbits);
574 } break;
575 default:
576 GRAND_BADOP;
577 break;
578 }
579
580 va_end(ap);
581 return (rc);
582 }
583
584 static octet gbyte(grand *r)
585 {
586 gctx *g = (gctx *)r;
587 octet o;
588 rand_getgood(&g->p, &o, 1);
589 return (o);
590 }
591
592 static uint32 gword(grand *r)
593 {
594 gctx *g = (gctx *)r;
595 octet b[4];
596 rand_getgood(&g->p, &b, sizeof(b));
597 return (LOAD32(b));
598 }
599
600 static void gfill(grand *r, void *p, size_t sz)
601 {
602 gctx *g = (gctx *)r;
603 rand_get(&g->p, p, sz);
604 }
605
606 static const grand_ops gops = {
607 "rand",
608 GRAND_CRYPTO, 0,
609 gmisc, gdestroy,
610 gword, gbyte, gword, grand_defaultrange, gfill
611 };
612
613 /* --- @rand_create@ --- *
614 *
615 * Arguments: ---
616 *
617 * Returns: Pointer to a generic generator.
618 *
619 * Use: Constructs a generic generator interface over a Catacomb
620 * entropy pool generator.
621 */
622
623 grand *rand_create(void)
624 {
625 gctx *g = S_CREATE(gctx);
626 g->r.ops = &gops;
627 rand_init(&g->p);
628 return (&g->r);
629 }
630
631 /*----- That's all, folks -------------------------------------------------*/