Merge branch '2.5.x'
[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*/);
aaf296c8
MW
166#endif
167
f1da6683
MW
168static quick__functype *pick_quick(void)
169{
a3ad4421
MW
170#if CPUFAM_X86 || CPUFAM_AMD64
171 DISPATCH_PICK_COND(rand_quick, rand_quick_x86ish_rdrand,
aaf296c8
MW
172 cpu_feature_p(CPUFEAT_X86_RDRAND));
173#endif
f1da6683
MW
174 DISPATCH_PICK_FALLBACK(rand_quick, trivial_quick);
175}
176
177int rand_quick(rand_pool *r) { RAND_RESOLVE(r); return (quick(r)); }
178
ac2fd5cd 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
192void 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
d03ab969 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
216void rand_key(rand_pool *r, const void *k, size_t sz)
217{
d6fab4f6
MW
218 HASH_CTX hc;
219 octet h[HASH_SZ];
220 static const char label[] = "Catacomb random pool key";
221
d03ab969 222 RAND_RESOLVE(r);
d6fab4f6
MW
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);
d03ab969 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
249void rand_add(rand_pool *r, const void *p, size_t sz, unsigned goodbits)
250{
251 const octet *c = p;
ba044e65 252 int i, rot;
d03ab969 253
79bc45d0 254 STATIC_ASSERT(RAND_POOLSZ == 128, "Polynomial doesn't match pool size");
d03ab969 255
256 RAND_RESOLVE(r);
257
ba044e65 258 i = r->i; rot = r->irot;
d03ab969 259
260 while (sz) {
261 octet o = *c++;
ba044e65 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]);
d03ab969 266 rot = (rot + 5) & 7;
267 i++; if (i >= RAND_POOLSZ) i -= RAND_POOLSZ;
d03ab969 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 *
45c0fd36 280 * Arguments: @rand_pool *r@ = pointer to a randomness pool
d03ab969 281 *
45c0fd36 282 * Returns: Estimate of the number of good bits remaining in the pool.
d03ab969 283 */
284
285unsigned 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
301void rand_gate(rand_pool *r)
302{
53073dfb 303 octet h[HASH_SZ], g[4];
d6fab4f6
MW
304 HASH_CTX hc;
305 CIPHER_CTX cc;
d03ab969 306
307 RAND_RESOLVE(r);
f1da6683 308 QUICK(r);
d03ab969 309
310 /* --- Hash up all the data in the pool --- */
311
d6fab4f6 312 HASH_INIT(&hc);
53073dfb 313 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
3f078a9c 314 HASH(&hc, r->k.k, RAND_KEYSZ);
d6fab4f6
MW
315 HASH(&hc, r->pool, RAND_POOLSZ);
316 HASH(&hc, r->buf, RAND_BUFSZ);
317 HASH_DONE(&hc, h);
318 BURN(hc);
d03ab969 319
320 /* --- Now mangle all of the data based on the hash --- */
321
d6fab4f6
MW
322 assert(CIPHER_KEYSZ <= HASH_SZ);
323 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
324 CIPHER_ENCRYPT(&cc, r->pool, r->pool, RAND_POOLSZ);
325 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
326 BURN(cc);
d03ab969 327
328 /* --- Reset the various state variables --- */
329
330 r->o = RAND_SECSZ;
331 r->obits += r->ibits;
332 if (r->obits > RAND_OBITS) {
333 r->ibits = r->obits - r->ibits;
334 r->obits = RAND_OBITS;
335 } else
336 r->ibits = 0;
f1da6683 337 QUICK(r);
d03ab969 338}
339
340/* --- @rand_stretch@ --- *
341 *
342 * Arguments: @rand_pool *r@ = pointer to a randomness pool
343 *
344 * Returns: ---
345 *
346 * Use: Stretches the contents of the output buffer by transforming
347 * it in a nonreversible way. This doesn't add any entropy
348 * worth speaking about, but it works well enough when the
349 * caller doesn't care about that sort of thing.
350 */
351
352void rand_stretch(rand_pool *r)
353{
53073dfb 354 octet h[HASH_SZ], g[4];
d6fab4f6
MW
355 HASH_CTX hc;
356 CIPHER_CTX cc;
d03ab969 357
358 RAND_RESOLVE(r);
f1da6683 359 QUICK(r);
d03ab969 360
361 /* --- Hash up all the data in the buffer --- */
362
d6fab4f6 363 HASH_INIT(&hc);
53073dfb 364 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
3f078a9c 365 HASH(&hc, r->k.k, RAND_KEYSZ);
d6fab4f6
MW
366 HASH(&hc, r->pool, RAND_POOLSZ);
367 HASH(&hc, r->buf, RAND_BUFSZ);
368 HASH_DONE(&hc, h);
369 BURN(hc);
d03ab969 370
d6fab4f6 371 /* --- Now mangle the buffer based on the hash --- */
d03ab969 372
dd188526 373 assert(CIPHER_KEYSZ <= HASH_SZ);
d6fab4f6
MW
374 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
375 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
376 BURN(cc);
d03ab969 377
378 /* --- Reset the various state variables --- */
379
380 r->o = RAND_SECSZ;
f1da6683 381 QUICK(r);
d03ab969 382}
383
384/* --- @rand_get@ --- *
385 *
386 * Arguments: @rand_pool *r@ = pointer to a randomness pool
387 * @void *p@ = pointer to output buffer
388 * @size_t sz@ = size of output buffer
389 *
390 * Returns: ---
391 *
392 * Use: Gets random data from the pool. The pool's contents can't be
393 * determined from the output of this function; nor can the
394 * output data be determined from a knowledge of the data input
395 * to the pool wihtout also having knowledge of the secret key.
396 * The good bits counter is decremented, although no special
397 * action is taken if it reaches zero.
398 */
399
400void rand_get(rand_pool *r, void *p, size_t sz)
401{
402 octet *o = p;
403
404 RAND_RESOLVE(r);
53073dfb 405 GENCHECK(r);
f1da6683 406 QUICK(r);
d03ab969 407
408 if (!sz)
409 return;
410 for (;;) {
411 if (r->o + sz <= RAND_BUFSZ) {
412 memcpy(o, r->buf + r->o, sz);
413 r->o += sz;
414 break;
415 } else {
416 size_t chunk = RAND_BUFSZ - r->o;
417 if (chunk) {
418 memcpy(o, r->buf + r->o, chunk);
419 sz -= chunk;
420 o += chunk;
421 }
422 rand_stretch(r);
423 }
424 }
425
426 if (r->obits > sz * 8)
427 r->obits -= sz * 8;
428 else
429 r->obits = 0;
430}
431
432/* --- @rand_getgood@ --- *
433 *
434 * Arguments: @rand_pool *r@ = pointer to a randomness pool
435 * @void *p@ = pointer to output buffer
436 * @size_t sz@ = size of output buffer
437 *
438 * Returns: ---
439 *
ac2fd5cd 440 * Use: Gets random data from the pool, ensuring that there are
441 * enough good bits. This interface isn't recommended: it makes
442 * the generator slow, and doesn't provide much more security
443 * than @rand_get@, assuming you've previously done a
444 * @rand_seed@.
d03ab969 445 */
446
447void rand_getgood(rand_pool *r, void *p, size_t sz)
448{
449 octet *o = p;
450
451 RAND_RESOLVE(r);
452
453 if (!sz)
454 return;
455 if (!r->s || !r->s->getnoise) {
456 rand_get(r, p, sz);
457 return;
458 }
53073dfb 459 GENCHECK(r);
f1da6683 460 QUICK(r);
d03ab969 461
462 while (sz) {
463 size_t chunk = sz;
464
465 if (chunk * 8 > r->obits) {
466 if (chunk * 8 > r->ibits + r->obits)
b056b793 467 do r->s->getnoise(r); while (r->ibits + r->obits < 256);
d03ab969 468 rand_gate(r);
469 if (chunk * 8 > r->obits)
470 chunk = r->obits / 8;
471 }
472
473 if (chunk + r->o > RAND_BUFSZ)
474 chunk = RAND_BUFSZ - r->o;
475
476 memcpy(o, r->buf + r->o, chunk);
aacbc1c6 477 r->o += chunk;
d03ab969 478 r->obits -= chunk * 8;
479 o += chunk;
480 sz -= chunk;
481 }
482}
483
aacbc1c6 484/*----- Generic random number generator interface -------------------------*/
485
486static void gdestroy(grand *r)
487{
a7a76ebd
MW
488 gctx *g = (gctx *)r;
489 if (g != &rand_global) {
ac2fd5cd 490 BURN(*g);
491 S_DESTROY(g);
492 }
aacbc1c6 493}
494
495static int gmisc(grand *r, unsigned op, ...)
496{
a7a76ebd 497 gctx *g = (gctx *)r;
aacbc1c6 498 va_list ap;
499 int rc = 0;
500 va_start(ap, op);
501
502 switch (op) {
503 case GRAND_CHECK:
504 switch (va_arg(ap, unsigned)) {
505 case GRAND_CHECK:
506 case GRAND_SEEDINT:
507 case GRAND_SEEDUINT32:
508 case GRAND_SEEDBLOCK:
b056b793 509 case GRAND_SEEDRAND:
aacbc1c6 510 case RAND_GATE:
511 case RAND_STRETCH:
512 case RAND_KEY:
513 case RAND_NOISESRC:
ac2fd5cd 514 case RAND_SEED:
838a6a51 515 case RAND_TIMER:
516 case RAND_GOODBITS:
990dafb1 517 case RAND_ADD:
aacbc1c6 518 rc = 1;
519 break;
520 default:
521 rc = 0;
522 break;
523 }
524 break;
525 case GRAND_SEEDINT: {
526 unsigned u = va_arg(ap, unsigned);
527 rand_add(&g->p, &u, sizeof(u), sizeof(u));
528 } break;
529 case GRAND_SEEDUINT32: {
530 uint32 i = va_arg(ap, uint32);
531 rand_add(&g->p, &i, sizeof(i), 4);
532 } break;
533 case GRAND_SEEDBLOCK: {
534 const void *p = va_arg(ap, const void *);
535 size_t sz = va_arg(ap, size_t);
536 rand_add(&g->p, p, sz, sz);
537 } break;
b056b793 538 case GRAND_SEEDRAND: {
539 grand *rr = va_arg(ap, grand *);
540 octet buf[16];
541 rr->ops->fill(rr, buf, sizeof(buf));
542 rand_add(&g->p, buf, sizeof(buf), 8);
543 } break;
aacbc1c6 544 case RAND_GATE:
545 rand_gate(&g->p);
546 break;
547 case RAND_STRETCH:
548 rand_stretch(&g->p);
549 break;
550 case RAND_KEY: {
551 const void *k = va_arg(ap, const void *);
552 size_t sz = va_arg(ap, size_t);
553 rand_key(&g->p, k, sz);
554 } break;
555 case RAND_NOISESRC:
556 rand_noisesrc(&g->p, va_arg(ap, const rand_source *));
557 break;
ac2fd5cd 558 case RAND_SEED:
559 rand_seed(&g->p, va_arg(ap, unsigned));
560 break;
838a6a51 561 case RAND_TIMER:
f1da6683 562 QUICK(&g->p);
838a6a51 563 break;
564 case RAND_GOODBITS:
565 rc = rand_goodbits(&g->p);
566 break;
990dafb1 567 case RAND_ADD: {
568 const void *p = va_arg(ap, const void *);
569 size_t sz = va_arg(ap, size_t);
570 unsigned goodbits = va_arg(ap, unsigned);
571 rand_add(&g->p, p, sz, goodbits);
572 } break;
aacbc1c6 573 default:
574 GRAND_BADOP;
575 break;
576 }
577
578 va_end(ap);
579 return (rc);
580}
581
582static octet gbyte(grand *r)
583{
a7a76ebd 584 gctx *g = (gctx *)r;
aacbc1c6 585 octet o;
586 rand_getgood(&g->p, &o, 1);
587 return (o);
588}
589
590static uint32 gword(grand *r)
591{
a7a76ebd 592 gctx *g = (gctx *)r;
aacbc1c6 593 octet b[4];
594 rand_getgood(&g->p, &b, sizeof(b));
595 return (LOAD32(b));
596}
597
598static void gfill(grand *r, void *p, size_t sz)
599{
a7a76ebd 600 gctx *g = (gctx *)r;
ac2fd5cd 601 rand_get(&g->p, p, sz);
aacbc1c6 602}
603
604static const grand_ops gops = {
605 "rand",
ac2fd5cd 606 GRAND_CRYPTO, 0,
aacbc1c6 607 gmisc, gdestroy,
44ff6c11 608 gword, gbyte, gword, grand_defaultrange, gfill
aacbc1c6 609};
610
aacbc1c6 611/* --- @rand_create@ --- *
612 *
613 * Arguments: ---
614 *
615 * Returns: Pointer to a generic generator.
616 *
617 * Use: Constructs a generic generator interface over a Catacomb
618 * entropy pool generator.
619 */
620
621grand *rand_create(void)
622{
ac2fd5cd 623 gctx *g = S_CREATE(gctx);
aacbc1c6 624 g->r.ops = &gops;
625 rand_init(&g->p);
626 return (&g->r);
627}
628
d03ab969 629/*----- That's all, folks -------------------------------------------------*/