rand/rand.c: Add support for x86 `RDRAND' instruction in `rand_quick'.
[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 __GNUC__ && (CPUFAM_X86 || CPUFAM_AMD64)
165 static 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
182 static quick__functype *pick_quick(void)
183 {
184 #if __GNUC__ && (CPUFAM_X86 || CPUFAM_AMD64)
185 DISPATCH_PICK_COND(rand_quick, rdrand_quick,
186 cpu_feature_p(CPUFEAT_X86_RDRAND));
187 #endif
188 DISPATCH_PICK_FALLBACK(rand_quick, trivial_quick);
189 }
190
191 int rand_quick(rand_pool *r) { RAND_RESOLVE(r); return (quick(r)); }
192
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
206 void 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
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
230 void rand_key(rand_pool *r, const void *k, size_t sz)
231 {
232 HASH_CTX hc;
233 octet h[HASH_SZ];
234 static const char label[] = "Catacomb random pool key";
235
236 RAND_RESOLVE(r);
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);
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
263 void rand_add(rand_pool *r, const void *p, size_t sz, unsigned goodbits)
264 {
265 const octet *c = p;
266 int i, rot;
267
268 #if RAND_POOLSZ != 128
269 # error Polynomial in rand_add is out of date. Fix it.
270 #endif
271
272 RAND_RESOLVE(r);
273
274 i = r->i; rot = r->irot;
275
276 while (sz) {
277 octet o = *c++;
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]);
282 rot = (rot + 5) & 7;
283 i++; if (i >= RAND_POOLSZ) i -= RAND_POOLSZ;
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 *
296 * Arguments: @rand_pool *r@ = pointer to a randomness pool
297 *
298 * Returns: Estimate of the number of good bits remaining in the pool.
299 */
300
301 unsigned 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
317 void rand_gate(rand_pool *r)
318 {
319 octet h[HASH_SZ], g[4];
320 HASH_CTX hc;
321 CIPHER_CTX cc;
322
323 RAND_RESOLVE(r);
324 QUICK(r);
325
326 /* --- Hash up all the data in the pool --- */
327
328 HASH_INIT(&hc);
329 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
330 HASH(&hc, r->pool, RAND_POOLSZ);
331 HASH(&hc, r->buf, RAND_BUFSZ);
332 HASH_DONE(&hc, h);
333 BURN(hc);
334
335 /* --- Now mangle all of the data based on the hash --- */
336
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);
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;
352 QUICK(r);
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
367 void rand_stretch(rand_pool *r)
368 {
369 octet h[HASH_SZ], g[4];
370 HASH_CTX hc;
371 CIPHER_CTX cc;
372
373 RAND_RESOLVE(r);
374 QUICK(r);
375
376 /* --- Hash up all the data in the buffer --- */
377
378 HASH_INIT(&hc);
379 STORE32(g, r->gen); HASH(&hc, g, sizeof(g));
380 HASH(&hc, r->pool, RAND_POOLSZ);
381 HASH(&hc, r->buf, RAND_BUFSZ);
382 HASH_DONE(&hc, h);
383 BURN(hc);
384
385 /* --- Now mangle the buffer based on the hash --- */
386
387 assert(CIPHER_KEYSZ <= HASH_SZ);
388 CIPHER_INIT(&cc, h, CIPHER_KEYSZ, 0);
389 CIPHER_ENCRYPT(&cc, r->buf, r->buf, RAND_BUFSZ);
390 BURN(cc);
391
392 /* --- Reset the various state variables --- */
393
394 r->o = RAND_SECSZ;
395 QUICK(r);
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
414 void rand_get(rand_pool *r, void *p, size_t sz)
415 {
416 octet *o = p;
417
418 RAND_RESOLVE(r);
419 GENCHECK(r);
420 QUICK(r);
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 *
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@.
459 */
460
461 void 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 }
473 GENCHECK(r);
474 QUICK(r);
475
476 while (sz) {
477 size_t chunk = sz;
478
479 if (chunk * 8 > r->obits) {
480 if (chunk * 8 > r->ibits + r->obits)
481 do r->s->getnoise(r); while (r->ibits + r->obits < 256);
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);
491 r->o += chunk;
492 r->obits -= chunk * 8;
493 o += chunk;
494 sz -= chunk;
495 }
496 }
497
498 /*----- Generic random number generator interface -------------------------*/
499
500 static void gdestroy(grand *r)
501 {
502 gctx *g = (gctx *)r;
503 if (g != &rand_global) {
504 BURN(*g);
505 S_DESTROY(g);
506 }
507 }
508
509 static int gmisc(grand *r, unsigned op, ...)
510 {
511 gctx *g = (gctx *)r;
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:
523 case GRAND_SEEDRAND:
524 case RAND_GATE:
525 case RAND_STRETCH:
526 case RAND_KEY:
527 case RAND_NOISESRC:
528 case RAND_SEED:
529 case RAND_TIMER:
530 case RAND_GOODBITS:
531 case RAND_ADD:
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;
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;
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;
572 case RAND_SEED:
573 rand_seed(&g->p, va_arg(ap, unsigned));
574 break;
575 case RAND_TIMER:
576 QUICK(&g->p);
577 break;
578 case RAND_GOODBITS:
579 rc = rand_goodbits(&g->p);
580 break;
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;
587 default:
588 GRAND_BADOP;
589 break;
590 }
591
592 va_end(ap);
593 return (rc);
594 }
595
596 static octet gbyte(grand *r)
597 {
598 gctx *g = (gctx *)r;
599 octet o;
600 rand_getgood(&g->p, &o, 1);
601 return (o);
602 }
603
604 static uint32 gword(grand *r)
605 {
606 gctx *g = (gctx *)r;
607 octet b[4];
608 rand_getgood(&g->p, &b, sizeof(b));
609 return (LOAD32(b));
610 }
611
612 static void gfill(grand *r, void *p, size_t sz)
613 {
614 gctx *g = (gctx *)r;
615 rand_get(&g->p, p, sz);
616 }
617
618 static const grand_ops gops = {
619 "rand",
620 GRAND_CRYPTO, 0,
621 gmisc, gdestroy,
622 gword, gbyte, gword, grand_defaultrange, gfill
623 };
624
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
635 grand *rand_create(void)
636 {
637 gctx *g = S_CREATE(gctx);
638 g->r.ops = &gops;
639 rand_init(&g->p);
640 return (&g->r);
641 }
642
643 /*----- That's all, folks -------------------------------------------------*/