3 * $Id: keygen.c,v 1.4 1997/12/08 15:29:27 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.4 1997/12/08 15:29:27 mdw
33 * Major update: make random number sources configurable. Generate
34 * warnings if there isn't enough randomness available.
36 * Revision 1.3 1997/09/17 15:29:28 mdw
37 * Mix the noise from the key timings with some other environmental noise
38 * (obtained from `noise_acquire') for a little bit more randomness.
40 * Revision 1.2 1997/08/04 10:24:23 mdw
41 * Sources placed under CVS control.
43 * Revision 1.1 1997/07/21 13:47:48 mdw
48 /*----- Header files ------------------------------------------------------*/
50 /* --- ANSI headers --- */
59 /* --- Unix headers --- */
61 #include <sys/types.h>
68 /* --- Local headers --- */
77 /*----- Static variables --------------------------------------------------*/
79 static struct termios kg__raw, kg__old; /* Terminal settings */
80 static int kg__tty; /* File handle for the terminal */
81 static FILE *kg__ttyfp; /* Stream pointer for terminal */
82 static unsigned int kg__flags; /* Various interesting flags */
85 kgFlag__cbreak = 1 /* Terminal is in cbreak mode */
88 /*----- Main code ---------------------------------------------------------*/
90 /* --- @kg__cbreak@ --- *
96 * Use: Makes the terminal return characters as soon as they're
100 void kg__cbreak(void)
102 /* --- Don't do this if I don't have to --- */
104 if (kg__flags & kgFlag__cbreak)
107 /* --- Fetch the old attributes, and remember them --- */
109 if (tcgetattr(kg__tty, &kg__old))
110 die("couldn't read terminal attributes: %s", strerror(errno));
111 memcpy(&kg__raw, &kg__old, sizeof(kg__raw));
113 /* --- Now modify them for raw mode --- */
115 kg__raw.c_lflag &= ~(ICANON | ECHO);
116 kg__raw.c_cc[VTIME] = 0;
117 kg__raw.c_cc[VMIN] = 1;
119 /* --- Remember the new state, and away we go --- */
121 kg__flags |= kgFlag__cbreak;
122 if (tcsetattr(kg__tty, TCSAFLUSH, &kg__raw))
123 die("couldn't set terminal attributes: %s", strerror(errno));
126 /* --- @kg__crepair@ --- *
132 * Use: Unbreaks a cbroken tty. Obvious, innit?
135 static void kg__crepair(void)
137 /* --- Don't do this if I don't have to --- */
139 if (~kg__flags & kgFlag__cbreak)
142 /* --- Reset the old attributes --- */
144 tcsetattr(kg__tty, TCSAFLUSH, &kg__old);
145 kg__flags &= ~kgFlag__cbreak;
148 /* --- @kg__signal@ --- *
150 * Arguments: @int sig@ = signal number
154 * Use: Tidies up if I get a signal.
157 static void kg__signal(int sig)
160 signal(sig, SIG_DFL);
164 /* --- @kgFmt__binary@ --- *
166 * Arguments: @unsigned char *k@ = pointer to key buffer
167 * @size_t bits@ = number of bits to write
168 * @FILE *fp@ = stream to write on
172 * Use: Writes bits on a stream.
175 static void kgFmt__binary(unsigned char *k, size_t bits, FILE *fp)
177 fwrite(k, 1, bits / 8, fp);
180 /* --- @kgFmt__base64@ --- *
182 * Arguments: @unsigned char *k@ = pointer to key buffer
183 * @size_t bits@ = number of bits to write
184 * @FILE *fp@ = stream to write on
188 * Use: Writes bits on a stream in an encoded way.
191 static void kgFmt__base64(unsigned char *k, size_t bits, FILE *fp)
193 static const char xlt[64] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
194 "abcdefghijklmnopqrstuvwxyz"
200 b = ((k[0] & 0xffu) << 16) | ((k[1] & 0xffu) << 8) | (k[2] & 0xffu);
203 putc(xlt[(b >> 18) & 0x3fu], fp);
204 putc(xlt[(b >> 12) & 0x3fu], fp);
205 putc(xlt[(b >> 6) & 0x3fu], fp);
206 putc(xlt[(b >> 0) & 0x3fu], fp);
207 if ((ll += 4) > 70) {
218 b = (b << 8) | (*k++ & 0xffu);
220 b = (b << 8) | (*k++ & 0xffu);
223 putc(xlt[(b >> 18) & 0x3fu], fp);
224 putc(xlt[(b >> 12) & 0x3fu], fp);
227 putc(xlt[(b >> 6) & 0x3fu], fp);
228 putc(xlt[(b >> 0) & 0x3fu], fp);
231 putc(xlt[(b >> 6) & 0x3fu], fp);
242 /* --- @kg__gen@ --- *
244 * Arguments: @unsigned char *ui@ = pointer to array to fill in
245 * @size_t sz@ = number of bits to generate
249 * Use: Uses key timings to generate random numbers. Maybe.
252 static void kg__gen(unsigned char *ui, size_t sz)
254 int bits = 32 < sz ? 32 : sz;
255 size_t wsz = (sz + 31u) & ~31u;
256 unsigned long last, ldiff = 0;
258 unsigned long fact = 1000000 / CLOCKS_PER_SEC;
261 "I need to get %lu random bits; I'll do this by timing your keypresses.\n"
262 "Please type some arbitrary text until I say `done'.\n",
267 gettimeofday(&tv, 0);
268 last = tv.tv_usec / fact + tv.tv_sec * fact;
275 /* --- Print current status --- */
277 fprintf(kg__ttyfp, "\r%5lu...", (unsigned long)sz);
280 /* --- Read the next character --- */
284 if (read(kg__tty, buff, sizeof(buff)) < 0)
285 die("couldn't read from terminal: %s", strerror(errno));
288 /* --- Fiddle with times --- *
290 * Read the time now. Turn it into 32 bits of useful information, and
291 * find the difference between that and the previous time. Compare this
292 * with the difference between the previous pair of keypresses.
299 gettimeofday(&tv, 0);
300 n = tv.tv_usec / fact + tv.tv_sec * fact;
309 D( printf("\nlast = %08lx, next = %08lx, ldiff = %08lx, nd = %08lx\n",
310 (unsigned long)last, (unsigned long)n,
311 (unsigned long)ldiff, (unsigned long)nd);
312 printf("xor = %08lx\n", (unsigned long)xor); )
317 /* --- Find the useful bits in this value --- *
319 * Find the least significant set bit in @bowl@ and chop it off. Then
320 * find the most significant set bit and chop that off two. The rest is
321 * probably interesting.
334 while (i && (xor & i) != 0) {
339 while (i && (xor & i) == 0) {
346 while ((orr & 1) == 0) {
357 /* --- Now add the bits in the mixing bowl to my stash --- *
359 * There are two cases:
361 * 1. I have more bits than will fit into the accumulator. Then I must
362 * put as many bits into the accumulator as will fit, store the
363 * accumulator, and remove the spent bits.
365 * 2. I have too few bits to fit in the accumulator. Then shift them
369 while (sz && useful) {
371 D( printf("got %i bits, need %i/%i: %8lx\n",
372 useful, bits, sz, (unsigned long)xor); )
374 if (useful >= bits) {
376 D( printf("shifted acc = %08lx\n"
377 " new bits = %08lx\n"
379 (unsigned long)(a << bits),
380 (unsigned long)(xor >> (useful - bits)),
381 (unsigned long)((a << bits) | (xor >> (useful - bits)))); )
383 a = (a << bits) | (xor >> (useful - bits));
396 D( printf("writing %02x\n", (a >> 24) & 0xffu); )
397 *ui++ = (a >> 24) & 0xffu;
403 bits = 32 < sz ? 32 : sz;
407 D( printf("shifted acc = %08lx\n"
408 " new bits = %08lx\n"
410 (unsigned long)(a << useful),
411 (unsigned long)(xor),
412 (unsigned long)((a << useful) | (xor))); )
413 a = (a << useful) | xor;
422 fputs("\rDone! \n", kg__ttyfp);
423 putc('\a', kg__ttyfp); fflush(kg__ttyfp);
429 * Arguments: @int argc@ = number of arguments
430 * @char *argv[]@ = array of arguments
432 * Returns: Zero if it worked, nonzero if it didn't.
434 * Use: Generates random numbers from the keyboard.
437 int main(int argc, char *argv[])
443 const char *file = 0;
451 /* --- Formats table --- */
455 void (*proc)(unsigned char *k, size_t bits, FILE *fp);
457 { "tx", tx_putBits },
458 { "hex", tx_putBits },
459 { "binary", kgFmt__binary },
460 { "base64", kgFmt__base64 },
464 void (*fmt)(unsigned char *, size_t, FILE *) = tx_putBits;
466 /* --- Explain who I am --- */
470 f |= f_envNoise | f_keyTimer;
472 /* --- Read arguments --- */
475 static struct option opts[] = {
476 { "help", 0, 0, 'h' },
477 { "bits", gFlag_argReq, 0, 'b' },
478 { "output", gFlag_argReq, 0, 'o' },
479 { "format", gFlag_argReq, 0, 'f' },
480 { "key-times", gFlag_negate|gFlag_argOpt, 0, 'k' },
481 { "env-noise", gFlag_negate, 0, 'e' },
485 int i = mdwopt(argc, argv, "hb:o:f:k+::e+", opts, 0, 0, gFlag_negation);
492 "Usage: %s [-h] [-|+ek] [-b BITS] [-o FILE] [-f FORMAT]\n"
494 "Generates BITS (by default, 128) random bits. The resulting number is\n"
495 "written to FILE, or standard output.\n\n"
496 "Randomness is taken from key-timings and environmental noise, although\n"
497 "you can disable either (or both) of these sources.\n\n"
498 "Options provided are:\n\n"
499 "-h, --help Display this help text\n"
500 "-b, --bits=BITS\t Generate BITS random bits instead of 128\n"
501 "-o, --output=FILE Write bits to FILE, not standard output\n"
502 "-f, --format=FORMAT Write bits in FORMAT:\n"
503 " tx, hex Hexadecimal\n"
504 " binary Raw binary\n"
505 " base64 Base64-encoded binary\n"
506 "-e, --[no-]env-noise Do [not] read environmental noise\n"
507 "-k, --[no-]key-times[=BITS] Do [not] read key timing information\n"
508 " (only read BITS bits from key timings)\n",
515 die("bad number of bits (illegible or zero)");
517 die("can only generate a whole number of 8-bit bytes");
524 for (i = 0; format[i].name; i++) {
525 const char *p = format[i].name, *q = optarg;
535 die("ambiguous format name: `%s'", optarg);
536 fmt = format[i].proc;
540 die("unknown format name: `%s'", optarg);
545 case 'e' | gFlag_negated:
551 keybits = atoi(optarg);
553 die("bad number of bits (illegible or zero)");
555 die("bad number of bits (must be multiple of 8)");
560 case 'k' | gFlag_negated:
569 /* --- Check the sanity of this request --- */
574 if (f & f_keyTimer) {
580 bits += 384; /* Estimate */
583 die("no randomness sources given");
585 moan("warning: randomness may not be sufficiently high");
589 fprintf(stderr, "Usage: %s [-opts]\n", quis());
593 /* --- Allocate memory --- */
596 size_t buff = sz / 8;
597 if (f & f_keyTimer && keybits > sz)
604 /* --- Fetch randomness from key timings --- */
606 if (f & f_keyTimer) {
608 /* --- Open the terminal --- *
610 * I'd like to be able to @fprintf@ to the terminal, so use @fopen@.
613 if ((kg__ttyfp = fopen("/dev/tty", "r+")) == 0)
614 die("couldn't open terminal: %s", strerror(errno));
615 kg__tty = fileno(kg__ttyfp);
617 /* --- Tidy up nicely if I die --- */
619 signal(SIGINT, kg__signal);
620 signal(SIGTERM, kg__signal);
623 /* --- Put the terminal into cbreak, read the key, and restore --- */
626 kg__gen(uip, keybits);
628 rand_add(uip, keybits / 8);
632 /* --- Find some noise from the environment too --- */
634 if (f & f_envNoise) {
639 /* --- Now write the number and exit --- */
641 rand_extract(uip, sz / 8);
642 D( fputs("*** ", fp); tx_putBits(uip, sz, stdout); )
644 /* --- Open the output file, if one is specified --- */
649 /* --- Open the file oddly --- *
651 * There's a good reason for this. I want to be able to @fprintf@ (for
652 * the benefit of @tx_putWords@ mainly) but I also want to ensure that
653 * only the user has read permissions for the file. So I'll use @open@
654 * with an appropriate mode and then @fdopen@ the file descriptor to
658 if ((fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0)
659 die("couldn't open output file: %s", strerror(errno));
660 if ((fp = fdopen(fd, "w")) == 0)
661 die("couldn't attach stream to output file: %s", strerror(errno));
668 memset(uip, 0, sz / 8); /* Burn temporary buffer */
673 /*----- That's all, folks -------------------------------------------------*/