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