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