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