3 * $Id: keygen.c,v 1.5 1998/01/12 16:46:05 mdw Exp $
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of `become'
14 * `Become' is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * `Become' is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with `become'; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Revision history --------------------------------------------------*
32 * Revision 1.5 1998/01/12 16:46:05 mdw
35 * Revision 1.4 1997/12/08 15:29:27 mdw
36 * Major update: make random number sources configurable. Generate
37 * warnings if there isn't enough randomness available.
39 * Revision 1.3 1997/09/17 15:29:28 mdw
40 * Mix the noise from the key timings with some other environmental noise
41 * (obtained from `noise_acquire') for a little bit more randomness.
43 * Revision 1.2 1997/08/04 10:24:23 mdw
44 * Sources placed under CVS control.
46 * Revision 1.1 1997/07/21 13:47:48 mdw
51 /*----- Header files ------------------------------------------------------*/
53 /* --- ANSI headers --- */
62 /* --- Unix headers --- */
64 #include <sys/types.h>
71 /* --- Local headers --- */
80 /*----- Static variables --------------------------------------------------*/
82 static struct termios kg__raw, kg__old; /* Terminal settings */
83 static int kg__tty; /* File handle for the terminal */
84 static FILE *kg__ttyfp; /* Stream pointer for terminal */
85 static unsigned int kg__flags; /* Various interesting flags */
88 kgFlag__cbreak = 1 /* Terminal is in cbreak mode */
91 /*----- Main code ---------------------------------------------------------*/
93 /* --- @kg__cbreak@ --- *
99 * Use: Makes the terminal return characters as soon as they're
103 void kg__cbreak(void)
105 /* --- Don't do this if I don't have to --- */
107 if (kg__flags & kgFlag__cbreak)
110 /* --- Fetch the old attributes, and remember them --- */
112 if (tcgetattr(kg__tty, &kg__old))
113 die("couldn't read terminal attributes: %s", strerror(errno));
114 memcpy(&kg__raw, &kg__old, sizeof(kg__raw));
116 /* --- Now modify them for raw mode --- */
118 kg__raw.c_lflag &= ~(ICANON | ECHO);
119 kg__raw.c_cc[VTIME] = 0;
120 kg__raw.c_cc[VMIN] = 1;
122 /* --- Remember the new state, and away we go --- */
124 kg__flags |= kgFlag__cbreak;
125 if (tcsetattr(kg__tty, TCSAFLUSH, &kg__raw))
126 die("couldn't set terminal attributes: %s", strerror(errno));
129 /* --- @kg__crepair@ --- *
135 * Use: Unbreaks a cbroken tty. Obvious, innit?
138 static void kg__crepair(void)
140 /* --- Don't do this if I don't have to --- */
142 if (~kg__flags & kgFlag__cbreak)
145 /* --- Reset the old attributes --- */
147 tcsetattr(kg__tty, TCSAFLUSH, &kg__old);
148 kg__flags &= ~kgFlag__cbreak;
151 /* --- @kg__signal@ --- *
153 * Arguments: @int sig@ = signal number
157 * Use: Tidies up if I get a signal.
160 static void kg__signal(int sig)
163 signal(sig, SIG_DFL);
167 /* --- @kgFmt__binary@ --- *
169 * Arguments: @unsigned char *k@ = pointer to key buffer
170 * @size_t bits@ = number of bits to write
171 * @FILE *fp@ = stream to write on
175 * Use: Writes bits on a stream.
178 static void kgFmt__binary(unsigned char *k, size_t bits, FILE *fp)
180 fwrite(k, 1, bits / 8, fp);
183 /* --- @kgFmt__base64@ --- *
185 * Arguments: @unsigned char *k@ = pointer to key buffer
186 * @size_t bits@ = number of bits to write
187 * @FILE *fp@ = stream to write on
191 * Use: Writes bits on a stream in an encoded way.
194 static void kgFmt__base64(unsigned char *k, size_t bits, FILE *fp)
196 static const char xlt[64] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
197 "abcdefghijklmnopqrstuvwxyz"
203 b = ((k[0] & 0xffu) << 16) | ((k[1] & 0xffu) << 8) | (k[2] & 0xffu);
206 putc(xlt[(b >> 18) & 0x3fu], fp);
207 putc(xlt[(b >> 12) & 0x3fu], fp);
208 putc(xlt[(b >> 6) & 0x3fu], fp);
209 putc(xlt[(b >> 0) & 0x3fu], fp);
210 if ((ll += 4) > 70) {
221 b = (b << 8) | (*k++ & 0xffu);
223 b = (b << 8) | (*k++ & 0xffu);
226 putc(xlt[(b >> 18) & 0x3fu], fp);
227 putc(xlt[(b >> 12) & 0x3fu], fp);
230 putc(xlt[(b >> 6) & 0x3fu], fp);
231 putc(xlt[(b >> 0) & 0x3fu], fp);
234 putc(xlt[(b >> 6) & 0x3fu], fp);
245 /* --- @kg__gen@ --- *
247 * Arguments: @unsigned char *ui@ = pointer to array to fill in
248 * @size_t sz@ = number of bits to generate
252 * Use: Uses key timings to generate random numbers. Maybe.
255 static void kg__gen(unsigned char *ui, size_t sz)
257 int bits = 32 < sz ? 32 : sz;
258 size_t wsz = (sz + 31u) & ~31u;
259 unsigned long last, ldiff = 0;
261 unsigned long fact = 1000000 / CLOCKS_PER_SEC;
264 "I need to get %lu random bits; I'll do this by timing your keypresses.\n"
265 "Please type some arbitrary text until I say `done'.\n",
270 gettimeofday(&tv, 0);
271 last = tv.tv_usec / fact + tv.tv_sec * fact;
278 /* --- Print current status --- */
280 fprintf(kg__ttyfp, "\r%5lu...", (unsigned long)sz);
283 /* --- Read the next character --- */
287 if (read(kg__tty, buff, sizeof(buff)) < 0)
288 die("couldn't read from terminal: %s", strerror(errno));
291 /* --- Fiddle with times --- *
293 * Read the time now. Turn it into 32 bits of useful information, and
294 * find the difference between that and the previous time. Compare this
295 * with the difference between the previous pair of keypresses.
302 gettimeofday(&tv, 0);
303 n = tv.tv_usec / fact + tv.tv_sec * fact;
312 D( printf("\nlast = %08lx, next = %08lx, ldiff = %08lx, nd = %08lx\n",
313 (unsigned long)last, (unsigned long)n,
314 (unsigned long)ldiff, (unsigned long)nd);
315 printf("xor = %08lx\n", (unsigned long)xor); )
320 /* --- Find the useful bits in this value --- *
322 * Find the least significant set bit in @bowl@ and chop it off. Then
323 * find the most significant set bit and chop that off two. The rest is
324 * probably interesting.
337 while (i && (xor & i) != 0) {
342 while (i && (xor & i) == 0) {
349 while ((orr & 1) == 0) {
360 /* --- Now add the bits in the mixing bowl to my stash --- *
362 * There are two cases:
364 * 1. I have more bits than will fit into the accumulator. Then I must
365 * put as many bits into the accumulator as will fit, store the
366 * accumulator, and remove the spent bits.
368 * 2. I have too few bits to fit in the accumulator. Then shift them
372 while (sz && useful) {
374 D( printf("got %i bits, need %i/%i: %8lx\n",
375 useful, bits, sz, (unsigned long)xor); )
377 if (useful >= bits) {
379 D( printf("shifted acc = %08lx\n"
380 " new bits = %08lx\n"
382 (unsigned long)(a << bits),
383 (unsigned long)(xor >> (useful - bits)),
384 (unsigned long)((a << bits) | (xor >> (useful - bits)))); )
386 a = (a << bits) | (xor >> (useful - bits));
399 D( printf("writing %02x\n", (a >> 24) & 0xffu); )
400 *ui++ = (a >> 24) & 0xffu;
406 bits = 32 < sz ? 32 : sz;
410 D( printf("shifted acc = %08lx\n"
411 " new bits = %08lx\n"
413 (unsigned long)(a << useful),
414 (unsigned long)(xor),
415 (unsigned long)((a << useful) | (xor))); )
416 a = (a << useful) | xor;
425 fputs("\rDone! \n", kg__ttyfp);
426 putc('\a', kg__ttyfp); fflush(kg__ttyfp);
432 * Arguments: @int argc@ = number of arguments
433 * @char *argv[]@ = array of arguments
435 * Returns: Zero if it worked, nonzero if it didn't.
437 * Use: Generates random numbers from the keyboard.
440 int main(int argc, char *argv[])
446 const char *file = 0;
454 /* --- Formats table --- */
458 void (*proc)(unsigned char *k, size_t bits, FILE *fp);
460 { "tx", tx_putBits },
461 { "hex", tx_putBits },
462 { "binary", kgFmt__binary },
463 { "base64", kgFmt__base64 },
467 void (*fmt)(unsigned char *, size_t, FILE *) = tx_putBits;
469 /* --- Explain who I am --- */
473 f |= f_envNoise | f_keyTimer;
475 /* --- Read arguments --- */
478 static struct option opts[] = {
479 { "help", 0, 0, 'h' },
480 { "bits", gFlag_argReq, 0, 'b' },
481 { "output", gFlag_argReq, 0, 'o' },
482 { "format", gFlag_argReq, 0, 'f' },
483 { "key-times", gFlag_negate|gFlag_argOpt, 0, 'k' },
484 { "env-noise", gFlag_negate, 0, 'e' },
488 int i = mdwopt(argc, argv, "hb:o:f:k+::e+", opts, 0, 0, gFlag_negation);
495 "Usage: %s [-h] [-|+ek] [-b BITS] [-o FILE] [-f FORMAT]\n"
497 "Generates BITS (by default, 128) random bits. The resulting number is\n"
498 "written to FILE, or standard output.\n\n"
499 "Randomness is taken from key-timings and environmental noise, although\n"
500 "you can disable either (or both) of these sources.\n\n"
501 "Options provided are:\n\n"
502 "-h, --help Display this help text\n"
503 "-b, --bits=BITS\t Generate BITS random bits instead of 128\n"
504 "-o, --output=FILE Write bits to FILE, not standard output\n"
505 "-f, --format=FORMAT Write bits in FORMAT:\n"
506 " tx, hex Hexadecimal\n"
507 " binary Raw binary\n"
508 " base64 Base64-encoded binary\n"
509 "-e, --[no-]env-noise Do [not] read environmental noise\n"
510 "-k, --[no-]key-times[=BITS] Do [not] read key timing information\n"
511 " (only read BITS bits from key timings)\n",
518 die("bad number of bits (illegible or zero)");
520 die("can only generate a whole number of 8-bit bytes");
527 for (i = 0; format[i].name; i++) {
528 const char *p = format[i].name, *q = optarg;
538 die("ambiguous format name: `%s'", optarg);
539 fmt = format[i].proc;
543 die("unknown format name: `%s'", optarg);
548 case 'e' | gFlag_negated:
554 keybits = atoi(optarg);
556 die("bad number of bits (illegible or zero)");
558 die("bad number of bits (must be multiple of 8)");
563 case 'k' | gFlag_negated:
572 /* --- Check the sanity of this request --- */
577 if (f & f_keyTimer) {
583 bits += 384; /* Estimate */
586 die("no randomness sources given");
588 moan("warning: randomness may not be sufficiently high");
592 fprintf(stderr, "Usage: %s [-opts]\n", quis());
596 /* --- Allocate memory --- */
599 size_t buff = sz / 8;
600 if (f & f_keyTimer && keybits > sz)
607 /* --- Fetch randomness from key timings --- */
609 if (f & f_keyTimer) {
611 /* --- Open the terminal --- *
613 * I'd like to be able to @fprintf@ to the terminal, so use @fopen@.
616 if ((kg__ttyfp = fopen("/dev/tty", "r+")) == 0)
617 die("couldn't open terminal: %s", strerror(errno));
618 kg__tty = fileno(kg__ttyfp);
620 /* --- Tidy up nicely if I die --- */
622 signal(SIGINT, kg__signal);
623 signal(SIGTERM, kg__signal);
626 /* --- Put the terminal into cbreak, read the key, and restore --- */
629 kg__gen(uip, keybits);
631 rand_add(uip, keybits / 8);
635 /* --- Find some noise from the environment too --- */
637 if (f & f_envNoise) {
642 /* --- Now write the number and exit --- */
644 rand_extract(uip, sz / 8);
645 D( fputs("*** ", fp); tx_putBits(uip, sz, stdout); )
647 /* --- Open the output file, if one is specified --- */
652 /* --- Open the file oddly --- *
654 * There's a good reason for this. I want to be able to @fprintf@ (for
655 * the benefit of @tx_putWords@ mainly) but I also want to ensure that
656 * only the user has read permissions for the file. So I'll use @open@
657 * with an appropriate mode and then @fdopen@ the file descriptor to
661 if ((fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0)
662 die("couldn't open output file: %s", strerror(errno));
663 if ((fp = fdopen(fd, "w")) == 0)
664 die("couldn't attach stream to output file: %s", strerror(errno));
671 memset(uip, 0, sz / 8); /* Burn temporary buffer */
676 /*----- That's all, folks -------------------------------------------------*/