3 * $Id: keygen.c,v 1.6 2003/09/17 13:17:23 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.6 2003/09/17 13:17:23 mdw
35 * Revision 1.5 1998/01/12 16:46:05 mdw
38 * Revision 1.4 1997/12/08 15:29:27 mdw
39 * Major update: make random number sources configurable. Generate
40 * warnings if there isn't enough randomness available.
42 * Revision 1.3 1997/09/17 15:29:28 mdw
43 * Mix the noise from the key timings with some other environmental noise
44 * (obtained from `noise_acquire') for a little bit more randomness.
46 * Revision 1.2 1997/08/04 10:24:23 mdw
47 * Sources placed under CVS control.
49 * Revision 1.1 1997/07/21 13:47:48 mdw
54 /*----- Header files ------------------------------------------------------*/
56 /* --- ANSI headers --- */
66 /* --- Unix headers --- */
68 #include <sys/types.h>
75 /* --- Local headers --- */
84 /*----- Static variables --------------------------------------------------*/
86 static struct termios kg__raw, kg__old; /* Terminal settings */
87 static int kg__tty; /* File handle for the terminal */
88 static FILE *kg__ttyfp; /* Stream pointer for terminal */
89 static unsigned int kg__flags; /* Various interesting flags */
92 kgFlag__cbreak = 1 /* Terminal is in cbreak mode */
95 /*----- Main code ---------------------------------------------------------*/
97 /* --- @kg__cbreak@ --- *
103 * Use: Makes the terminal return characters as soon as they're
107 void kg__cbreak(void)
109 /* --- Don't do this if I don't have to --- */
111 if (kg__flags & kgFlag__cbreak)
114 /* --- Fetch the old attributes, and remember them --- */
116 if (tcgetattr(kg__tty, &kg__old))
117 die("couldn't read terminal attributes: %s", strerror(errno));
118 memcpy(&kg__raw, &kg__old, sizeof(kg__raw));
120 /* --- Now modify them for raw mode --- */
122 kg__raw.c_lflag &= ~(ICANON | ECHO);
123 kg__raw.c_cc[VTIME] = 0;
124 kg__raw.c_cc[VMIN] = 1;
126 /* --- Remember the new state, and away we go --- */
128 kg__flags |= kgFlag__cbreak;
129 if (tcsetattr(kg__tty, TCSAFLUSH, &kg__raw))
130 die("couldn't set terminal attributes: %s", strerror(errno));
133 /* --- @kg__crepair@ --- *
139 * Use: Unbreaks a cbroken tty. Obvious, innit?
142 static void kg__crepair(void)
144 /* --- Don't do this if I don't have to --- */
146 if (~kg__flags & kgFlag__cbreak)
149 /* --- Reset the old attributes --- */
151 tcsetattr(kg__tty, TCSAFLUSH, &kg__old);
152 kg__flags &= ~kgFlag__cbreak;
155 /* --- @kg__signal@ --- *
157 * Arguments: @int sig@ = signal number
161 * Use: Tidies up if I get a signal.
164 static void kg__signal(int sig)
167 signal(sig, SIG_DFL);
171 /* --- @kgFmt__binary@ --- *
173 * Arguments: @unsigned char *k@ = pointer to key buffer
174 * @size_t bits@ = number of bits to write
175 * @FILE *fp@ = stream to write on
179 * Use: Writes bits on a stream.
182 static void kgFmt__binary(unsigned char *k, size_t bits, FILE *fp)
184 fwrite(k, 1, bits / 8, fp);
187 /* --- @kgFmt__base64@ --- *
189 * Arguments: @unsigned char *k@ = pointer to key buffer
190 * @size_t bits@ = number of bits to write
191 * @FILE *fp@ = stream to write on
195 * Use: Writes bits on a stream in an encoded way.
198 static void kgFmt__base64(unsigned char *k, size_t bits, FILE *fp)
200 static const char xlt[64] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
201 "abcdefghijklmnopqrstuvwxyz"
207 b = ((k[0] & 0xffu) << 16) | ((k[1] & 0xffu) << 8) | (k[2] & 0xffu);
210 putc(xlt[(b >> 18) & 0x3fu], fp);
211 putc(xlt[(b >> 12) & 0x3fu], fp);
212 putc(xlt[(b >> 6) & 0x3fu], fp);
213 putc(xlt[(b >> 0) & 0x3fu], fp);
214 if ((ll += 4) > 70) {
225 b = (b << 8) | (*k++ & 0xffu);
227 b = (b << 8) | (*k++ & 0xffu);
230 putc(xlt[(b >> 18) & 0x3fu], fp);
231 putc(xlt[(b >> 12) & 0x3fu], fp);
234 putc(xlt[(b >> 6) & 0x3fu], fp);
235 putc(xlt[(b >> 0) & 0x3fu], fp);
238 putc(xlt[(b >> 6) & 0x3fu], fp);
249 /* --- @kg__gen@ --- *
251 * Arguments: @unsigned char *ui@ = pointer to array to fill in
252 * @size_t sz@ = number of bits to generate
256 * Use: Uses key timings to generate random numbers. Maybe.
259 static void kg__gen(unsigned char *ui, size_t sz)
261 int bits = 32 < sz ? 32 : sz;
262 size_t wsz = (sz + 31u) & ~31u;
263 unsigned long last, ldiff = 0;
265 unsigned long fact = 1000000 / CLOCKS_PER_SEC;
268 "I need to get %lu random bits; I'll do this by timing your keypresses.\n"
269 "Please type some arbitrary text until I say `done'.\n",
274 gettimeofday(&tv, 0);
275 last = tv.tv_usec / fact + tv.tv_sec * fact;
282 /* --- Print current status --- */
284 fprintf(kg__ttyfp, "\r%5lu...", (unsigned long)sz);
287 /* --- Read the next character --- */
291 if (read(kg__tty, buff, sizeof(buff)) < 0)
292 die("couldn't read from terminal: %s", strerror(errno));
295 /* --- Fiddle with times --- *
297 * Read the time now. Turn it into 32 bits of useful information, and
298 * find the difference between that and the previous time. Compare this
299 * with the difference between the previous pair of keypresses.
306 gettimeofday(&tv, 0);
307 n = tv.tv_usec / fact + tv.tv_sec * fact;
316 D( printf("\nlast = %08lx, next = %08lx, ldiff = %08lx, nd = %08lx\n",
317 (unsigned long)last, (unsigned long)n,
318 (unsigned long)ldiff, (unsigned long)nd);
319 printf("xor = %08lx\n", (unsigned long)xor); )
324 /* --- Find the useful bits in this value --- *
326 * Find the least significant set bit in @bowl@ and chop it off. Then
327 * find the most significant set bit and chop that off two. The rest is
328 * probably interesting.
341 while (i && (xor & i) != 0) {
346 while (i && (xor & i) == 0) {
353 while ((orr & 1) == 0) {
364 /* --- Now add the bits in the mixing bowl to my stash --- *
366 * There are two cases:
368 * 1. I have more bits than will fit into the accumulator. Then I must
369 * put as many bits into the accumulator as will fit, store the
370 * accumulator, and remove the spent bits.
372 * 2. I have too few bits to fit in the accumulator. Then shift them
376 while (sz && useful) {
378 D( printf("got %i bits, need %i/%i: %8lx\n",
379 useful, bits, sz, (unsigned long)xor); )
381 if (useful >= bits) {
383 D( printf("shifted acc = %08lx\n"
384 " new bits = %08lx\n"
386 (unsigned long)(a << bits),
387 (unsigned long)(xor >> (useful - bits)),
388 (unsigned long)((a << bits) | (xor >> (useful - bits)))); )
390 a = (a << bits) | (xor >> (useful - bits));
403 D( printf("writing %02x\n", (a >> 24) & 0xffu); )
404 *ui++ = (a >> 24) & 0xffu;
410 bits = 32 < sz ? 32 : sz;
414 D( printf("shifted acc = %08lx\n"
415 " new bits = %08lx\n"
417 (unsigned long)(a << useful),
418 (unsigned long)(xor),
419 (unsigned long)((a << useful) | (xor))); )
420 a = (a << useful) | xor;
429 fputs("\rDone! \n", kg__ttyfp);
430 putc('\a', kg__ttyfp); fflush(kg__ttyfp);
436 * Arguments: @int argc@ = number of arguments
437 * @char *argv[]@ = array of arguments
439 * Returns: Zero if it worked, nonzero if it didn't.
441 * Use: Generates random numbers from the keyboard.
444 int main(int argc, char *argv[])
450 const char *file = 0;
458 /* --- Formats table --- */
462 void (*proc)(unsigned char *k, size_t bits, FILE *fp);
464 { "tx", tx_putBits },
465 { "hex", tx_putBits },
466 { "binary", kgFmt__binary },
467 { "base64", kgFmt__base64 },
471 void (*fmt)(unsigned char *, size_t, FILE *) = tx_putBits;
473 /* --- Explain who I am --- */
477 f |= f_envNoise | f_keyTimer;
479 /* --- Read arguments --- */
482 static struct option opts[] = {
483 { "help", 0, 0, 'h' },
484 { "bits", gFlag_argReq, 0, 'b' },
485 { "output", gFlag_argReq, 0, 'o' },
486 { "format", gFlag_argReq, 0, 'f' },
487 { "key-times", gFlag_negate|gFlag_argOpt, 0, 'k' },
488 { "env-noise", gFlag_negate, 0, 'e' },
492 int i = mdwopt(argc, argv, "hb:o:f:k+::e+", opts, 0, 0, gFlag_negation);
499 "Usage: %s [-h] [-|+ek] [-b BITS] [-o FILE] [-f FORMAT]\n"
501 "Generates BITS (by default, 128) random bits. The resulting number is\n"
502 "written to FILE, or standard output.\n\n"
503 "Randomness is taken from key-timings and environmental noise, although\n"
504 "you can disable either (or both) of these sources.\n\n"
505 "Options provided are:\n\n"
506 "-h, --help Display this help text\n"
507 "-b, --bits=BITS\t Generate BITS random bits instead of 128\n"
508 "-o, --output=FILE Write bits to FILE, not standard output\n"
509 "-f, --format=FORMAT Write bits in FORMAT:\n"
510 " tx, hex Hexadecimal\n"
511 " binary Raw binary\n"
512 " base64 Base64-encoded binary\n"
513 "-e, --[no-]env-noise Do [not] read environmental noise\n"
514 "-k, --[no-]key-times[=BITS] Do [not] read key timing information\n"
515 " (only read BITS bits from key timings)\n",
522 die("bad number of bits (illegible or zero)");
524 die("can only generate a whole number of 8-bit bytes");
531 for (i = 0; format[i].name; i++) {
532 const char *p = format[i].name, *q = optarg;
542 die("ambiguous format name: `%s'", optarg);
543 fmt = format[i].proc;
547 die("unknown format name: `%s'", optarg);
552 case 'e' | gFlag_negated:
558 keybits = atoi(optarg);
560 die("bad number of bits (illegible or zero)");
562 die("bad number of bits (must be multiple of 8)");
567 case 'k' | gFlag_negated:
576 /* --- Check the sanity of this request --- */
581 if (f & f_keyTimer) {
587 bits += 384; /* Estimate */
590 die("no randomness sources given");
592 moan("warning: randomness may not be sufficiently high");
596 fprintf(stderr, "Usage: %s [-opts]\n", quis());
600 /* --- Allocate memory --- */
603 size_t buff = sz / 8;
604 if (f & f_keyTimer && keybits > sz)
611 /* --- Fetch randomness from key timings --- */
613 if (f & f_keyTimer) {
615 /* --- Open the terminal --- *
617 * I'd like to be able to @fprintf@ to the terminal, so use @fopen@.
620 if ((kg__ttyfp = fopen("/dev/tty", "r+")) == 0)
621 die("couldn't open terminal: %s", strerror(errno));
622 kg__tty = fileno(kg__ttyfp);
624 /* --- Tidy up nicely if I die --- */
626 signal(SIGINT, kg__signal);
627 signal(SIGTERM, kg__signal);
630 /* --- Put the terminal into cbreak, read the key, and restore --- */
633 kg__gen(uip, keybits);
635 rand_add(uip, keybits / 8);
639 /* --- Find some noise from the environment too --- */
641 if (f & f_envNoise) {
646 /* --- Now write the number and exit --- */
648 rand_extract(uip, sz / 8);
649 D( fputs("*** ", fp); tx_putBits(uip, sz, stdout); )
651 /* --- Open the output file, if one is specified --- */
656 /* --- Open the file oddly --- *
658 * There's a good reason for this. I want to be able to @fprintf@ (for
659 * the benefit of @tx_putWords@ mainly) but I also want to ensure that
660 * only the user has read permissions for the file. So I'll use @open@
661 * with an appropriate mode and then @fdopen@ the file descriptor to
665 if ((fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0)
666 die("couldn't open output file: %s", strerror(errno));
667 if ((fp = fdopen(fd, "w")) == 0)
668 die("couldn't attach stream to output file: %s", strerror(errno));
675 memset(uip, 0, sz / 8); /* Burn temporary buffer */
680 /*----- That's all, folks -------------------------------------------------*/