Makefile: practice pedantic particularity
[otpcli.git] / otpcli.c
bloba4a0233e028a73fb3ead40b9076adb310cfedc74
1 /*
3 otpcli.c - one time password command line interface
4 Copyright (C) 2023 Kyle J. McKay
5 All rights reserved
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
10 1. Redistributions of source code must retain the above copyright notice,
11 this list of conditions and the following disclaimer.
13 2. Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
17 3. Neither the name of the copyright holder nor the names of its
18 contributors may be used to endorse or promote products derived from
19 this software without specific prior written permission.
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
25 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE.
35 #include <stdarg.h>
36 #include <stddef.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <sys/select.h>
41 #include <fcntl.h>
42 #include <locale.h>
43 #include <string.h>
44 #include <time.h>
45 #include <unistd.h>
46 #include "lt1.h"
47 #include "lt256.h"
48 #include "lt512.h"
50 #define appnm() "otpcli"
52 static void
53 outversion(void)
55 printf("%s version 1.0\n", appnm());
58 static void
59 usage( int ec,
60 int full)
62 FILE *outf = ec ? stderr : stdout;
63 (void)fprintf(outf,
65 #define USAGEOPTS "hVi" "s:3:b:" "c:p:0:H:D:T:" "-9l"
67 "usage: %s [-hVi] [option...] -s [@]<hex>] | -3 [@]<base32> | -b <filename>\n"
68 "-h show short help and exit\n"
69 "-hh show full help and exit\n"
70 "-V show program version and exit\n"
71 "-i interactively show countdown of time remaining and update password\n"
72 "-s <hex> is hexadecimal secret or with '@' name of file with hex secret\n"
73 "-3 <base32> is base 32 secret or with '@' name of file with base32 secret\n"
74 "-b <filename> (leading '@' ignored) is file containing exact binary secret\n"
75 "-c <c> hotp mode with counter value <c> (leading 0x hex, 0 octal else decimal)\n"
76 "-p <p> use period <p> (in seconds) instead of default period of 30 seconds\n"
77 "-0 <o> use T0 time <o> (in seconds) instead of default T0 time of 0 seconds\n"
78 "-H <h> use hash <h> (sha1, sha256 or sha512) instead of default sha1\n"
79 "-D <d> show <d> (6, 7 or 8) password digits instead of default 6\n"
80 "-T <t> pretend that the time() function always returns <t> (for testing)\n"
81 "-9 use byte 19 for dynamic reduction for sha256/sha512 (for broken sites)\n"
82 "-l use little endian counter (for broken sites)\n"
83 ,appnm());
85 if (full) (void)fprintf(outf,
86 "\n"
87 "Exactly one of -s, -3 or -b must be given that specifies the secret to be used\n"
88 "to generate the one time password. Keep the secret in a file and pass the file\n"
89 "name preceded with an '@' as the argument to avoid exposing the secret on the\n"
90 "command line. Hex mode (-s) will skip an optional leading '0x' and both hex\n"
91 "mode (-s) and base 32 mode (-3) ignore whitespace while reading the value.\n"
92 "Using a file name of '-' reads from standard input (e.g. -3@-).\n"
93 "\n"
94 "The default mode is a time-based one time password (totp) using hash algorithm\n"
95 "sha1, a time zero of 0, a period of 30 seconds and non-interactively showing a\n"
96 "6 digit password. This is the mode most commonly used by sites.\n"
97 "\n"
98 "Using the -c option activates hmac-based one time password (hotp) mode in which\n"
99 "case the proper value of <c> must be given in order to get the correct password.\n"
100 "The -i, -p, -0 and -T options are not available in hotp mode.\n"
101 "\n"
102 "When using -H sha256 or -H sha512, it may be necessary to use the -9 option to\n"
103 "correctly match the values generated by some broken sites that always use byte\n"
104 "19 when doing dynamic reduction rather than the last byte of the hash value.\n"
105 "Sites that incorrectly format the counter value as little-endian instead of\n"
106 "correctly big-endian will require -l in order to match their values.\n"
107 "\n"
108 "The interactive (-i) mode (only for totp) shows the generated password and\n"
109 "seconds remaining as usual but then updates the seconds remaining each second\n"
110 "until the current period expires and then generates and shows the next password\n"
111 "and restarts the countdown. Exit interactive mode with <return> or <ctrl-c>.\n"
112 "\n"
113 "Given the URI:\n"
114 " otpauth://totp/test:id@do.main?secret=JBSWY3DPEHPK3XPX&issuer=test\n"
115 "It's sufficient to simply use:\n"
116 " otpcli -3 JBSWY3DPEHPK3XPX\n"
117 "Also perhaps adding the -i option to activate the interactive output mode.\n"
118 "\n"
119 "Output is the password and, if in totp mode, a <space> and the number of seconds\n"
120 "remaining (with an 's' suffix).\n"
123 exit(ec);
126 struct hmac_s;
127 typedef struct opts_s {
128 uint64_t counter;
129 uint64_t period;
130 uint64_t t0;
131 uint64_t testT;
132 const struct hmac_s *otphash;
133 unsigned digits;
134 char *sval, *b32val, *binval;
135 unsigned char *secret;
136 size_t secretSz;
137 int iFileNo;
138 struct {
139 unsigned counter : 1;
140 unsigned period : 1;
141 unsigned t0 : 1;
142 unsigned testT : 1;
143 unsigned i : 1;
144 unsigned b19 : 1;
145 unsigned l : 1;
146 } set;
147 } opts_t;
148 static opts_t opts;
150 #define MAX_HASH_OUTPUT 64 /* sha512 */
151 #define MAX_BLOCK_SIZE 128 /* sha512 */
153 typedef union HMAC_CTX_u {
154 SHA1_CTX sha1;
155 SHA256_CTX sha256;
156 SHA512_CTX sha512;
157 } HMAC_CTX_t;
158 typedef int (*hmacinitfunc_t)(HMAC_CTX_t *);
159 typedef int (*hmacupdatefunc_t)(HMAC_CTX_t *, const void *, size_t);
160 typedef int (*hmacfinalfunc_t)(unsigned char *, HMAC_CTX_t *);
161 typedef unsigned char *(*hmacfunc_t)(const void *, size_t, unsigned char *);
162 typedef enum otphash_e {
163 otphash_sha1 = 0,
164 otphash_sha256 = 1,
165 otphash_sha512 = 2
166 } otphash_t;
167 typedef struct hmac_s {
168 otphash_t otphash;
169 unsigned outSize;
170 unsigned blockSize;
171 hmacinitfunc_t hashinitfunc;
172 hmacupdatefunc_t hashupdatefunc;
173 hmacfinalfunc_t hashfinalfunc;
174 hmacfunc_t hashfunc;
175 } hmac_t;
176 static const hmac_t otphash_table[3] = {
177 {otphash_sha1, 20, 64, (hmacinitfunc_t)SHA1_Init,
178 (hmacupdatefunc_t)SHA1_Update,
179 (hmacfinalfunc_t)SHA1_Final, SHA1},
180 {otphash_sha256, 32, 64, (hmacinitfunc_t)SHA256_Init,
181 (hmacupdatefunc_t)SHA256_Update,
182 (hmacfinalfunc_t)SHA256_Final, SHA256},
183 {otphash_sha512, 64, 128, (hmacinitfunc_t)SHA512_Init,
184 (hmacupdatefunc_t)SHA512_Update,
185 (hmacfinalfunc_t)SHA512_Final, SHA512}
188 typedef unsigned char counter_t[8];
189 typedef unsigned char hashdata_t[MAX_HASH_OUTPUT];
191 static void parseopts(int *, char ***, opts_t *);
192 static int isws(unsigned);
193 static int isrdtty(int);
194 static void flushinput(int);
195 static unsigned char *readfile(const char *, size_t *, int);
196 static unsigned char *decodehex(const void *, size_t, size_t *);
197 static unsigned char *decodebase32(const void *, size_t, size_t *);
198 static unsigned char *calchmac(unsigned char *, const hmac_t *, const void *, size_t, const void *, size_t, size_t *);
199 static void storecounter(uint64_t, counter_t);
200 static unsigned long calcpw(const unsigned char *, size_t, unsigned);
201 static void die(const char *, ...);
202 static void edie(int, const char *, ...);
205 main( int argc,
206 char **argv)
208 counter_t cntr;
209 hashdata_t hmac;
210 size_t hmacsz = 0;
211 unsigned long pword;
213 parseopts(&argc, &argv, &opts);
214 if (opts.set.counter) {
215 storecounter(opts.counter, cntr);
216 if (!calchmac(hmac, opts.otphash, opts.secret, opts.secretSz, cntr, sizeof(cntr), &hmacsz))
217 die("calchmac failed\n");
218 pword = calcpw(hmac, hmacsz, opts.digits);
219 printf("%0*lu\n", (int)opts.digits, pword);
220 } else {
221 uint64_t tnow = opts.set.testT ? opts.testT : (uint64_t)time(NULL);
222 uint64_t cval, left;
223 const char *epre = "", *pre = "", *post = "\n";
225 if (opts.set.i)
226 post = "";
227 totploop:
228 if (tnow < opts.t0)
229 edie(2, "%s%s: error: time now (%llu) is less than time 0 (%llu)\n", epre,
230 appnm(), (unsigned long long)tnow, (unsigned long long)opts.t0);
231 cval = (tnow - opts.t0) / opts.period;
232 left = (tnow - opts.t0) - (cval * opts.period);
233 left = opts.period - left;
234 storecounter(cval, cntr);
235 if (!calchmac(hmac, opts.otphash, opts.secret, opts.secretSz, cntr, sizeof(cntr), &hmacsz))
236 die("calchmac failed\n");
237 pword = calcpw(hmac, hmacsz, opts.digits);
238 printf("%s%0*lu %llus%s", pre, (int)opts.digits, pword, (unsigned long long)left, post);
239 fflush(stdout);
240 if (opts.set.i) {
241 fd_set fds;
242 struct timeval tv;
243 uint64_t tnoworig = tnow;
244 int slct;
246 epre = "\n";
247 pre = "\r";
248 post = " \b\b\b\b\b\b\b\b\b\b";
249 waitagain:
250 FD_ZERO(&fds);
251 FD_SET(opts.iFileNo, &fds);
252 tv.tv_sec = 0;
253 tv.tv_usec = 500000;
254 slct = select(opts.iFileNo + 1, &fds, NULL, NULL, &tv);
255 if (slct == -1)
256 die("\n%s: error: select failed\n", appnm());
257 if (!slct) {
258 tnow = (uint64_t)time(NULL);
259 if (tnow == tnoworig)
260 goto waitagain;
261 goto totploop;
263 flushinput(opts.iFileNo);
264 /*printf("\n");*/
267 free(opts.secret);
268 return 0;
271 static void
272 storecounter(
273 uint64_t cval,
274 counter_t cbytes)
276 unsigned char *cp = cbytes;
277 int i, incr;
279 if (opts.set.l) {
280 incr = 1;
281 } else {
282 incr = -1;
283 cp += 7;
285 for (i = 0; i < 8; ++i) {
286 *cp = (unsigned char)(cval & 0xFF);
287 cp += incr;
288 cval >>= 8;
292 static unsigned long
293 calcpw(
294 const unsigned char *hmac,
295 size_t hmacsz,
296 unsigned digs)
298 unsigned idx;
299 uint32_t reduced;
300 const unsigned char *p;
302 if (!hmac || hmacsz < 20)
303 die("invalid calcpw arguments\n");
304 if (digs < 6 || digs > 8)
305 die("invalid calcpw digits of %u\n", digs);
306 idx = opts.set.b19 ? 19 : (unsigned)(hmacsz - 1);
307 p = hmac + (hmac[idx] & 0xF);
308 reduced = ((uint32_t)(p[0] & 0x7F) << 24) |
309 ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
310 if (digs == 6)
311 return (unsigned long)(reduced % 1000000LU);
312 if (digs == 7)
313 return (unsigned long)(reduced % 10000000LU);
314 return (unsigned long)(reduced % 100000000LU);
317 static void
318 setupapp(
319 const char *argv0)
321 putenv("POSIXLY_CORRECT=1"); /* for incompliant c libraries */
322 tzset(); /* use the requested time zone if any */
323 setlocale(LC_NUMERIC, ""); /* allows ' to work in printf formats */
324 opterr = 0; /* we show our own errors */
325 if (!argv0 || !*argv0)
326 return;
327 /* possibly extract base name of argv0 here in the future */
330 static int
331 streqcase(
332 const char *s1_,
333 const char *s2_)
335 const unsigned char *s1 = (unsigned char *)s1_;
336 const unsigned char *s2 = (unsigned char *)s2_;
337 unsigned char uc1, uc2;
339 if (!s1)
340 return s1 == s2;
341 if (!s2)
342 return 0; /* only match is NULL s1, but that can't get here */
343 do {
344 uc1 = *s1++;
345 uc1 += (unsigned char)'A' <= uc1 && uc1 <= (unsigned char)'Z' ?
346 (unsigned char)('a' - 'A') : 0;
347 uc2 = *s2++;
348 uc2 += (unsigned char)'A' <= uc2 && uc2 <= (unsigned char)'Z' ?
349 (unsigned char)('a' - 'A') : 0;
350 } while (uc1 && uc1 == uc2);
351 return uc1 == uc2;
354 static void
355 initoutopts(
356 struct opts_s *opts)
358 memset(opts, 0, sizeof(*opts));
359 opts->period = 30U;
360 opts->digits = 6U;
361 opts->otphash = &otphash_table[otphash_sha1];
364 static void
365 parseopts(
366 int *argc,
367 char ***argv,
368 opts_t *outopts)
370 int ch;
371 int opt_h = 0;
372 int opt_V = 0;
373 long long llv = 0;
374 char *endp;
376 setupapp((*argv)[0]);
377 initoutopts(outopts);
378 while ((ch = getopt(*argc, *argv, ":" USAGEOPTS)) != -1) {
379 switch (ch) {
380 case '?': edie(2, "%s: error: unknown option -%c (try -h)\n", appnm(), optopt);
381 case ':': edie(2, "%s: error: missing argument for option -%c (try -h)\n", appnm(), optopt);
382 case 'h': ++opt_h; break;
383 case 'V': opt_V = 1; break;
384 case 'i': outopts->set.i = 1U; break;
385 case '9': outopts->set.b19 = 1U; break;
386 case 'l': outopts->set.l = 1U; break;
387 case 's':
388 if (optarg)
389 while (*optarg == ' ' || *optarg == '\t')
390 ++optarg;
391 if (!optarg || !*optarg)
392 needarg:
393 edie(2, "%s: error: -%c must have a non-empty argument (try -h)\n",
394 appnm(), ch);
395 outopts->sval = optarg;
396 break;
397 case '3':
398 if (optarg)
399 while (*optarg == ' ' || *optarg == '\t')
400 ++optarg;
401 if (!optarg || !*optarg)
402 goto needarg;
403 outopts->b32val = optarg;
404 break;
405 case 'b':
406 if (optarg)
407 while (*optarg == ' ' || *optarg == '\t')
408 ++optarg;
409 if (optarg && *optarg == '@')
410 ++optarg; /* ignore leading '@' */
411 if (!optarg || !*optarg)
412 goto needarg;
413 outopts->binval = optarg;
414 break;
415 case 'c':
416 if (optarg)
417 while (*optarg == ' ' || *optarg == '\t')
418 ++optarg;
419 if (!optarg || !*optarg)
420 goto needarg;
421 llv = strtoll(optarg, &endp, 0);
422 if (endp != optarg)
423 while (*endp == ' ' || *endp == '\t')
424 ++endp;
425 if (endp == optarg || llv < 0)
426 badarg:
427 edie(2, "%s: error: invalid argument for option -%c (try -h)\n",
428 appnm(), ch);
429 outopts->set.counter = 1U;
430 outopts->counter = (uint64_t)(unsigned long long)llv;
431 break;
432 case 'p':
433 if (optarg)
434 while (*optarg == ' ' || *optarg == '\t')
435 ++optarg;
436 if (!optarg || !*optarg)
437 goto needarg;
438 llv = strtoll(optarg, &endp, 0);
439 if (endp != optarg)
440 while (*endp == ' ' || *endp == '\t')
441 ++endp;
442 if (endp == optarg || llv <= 0)
443 goto badarg;
444 outopts->set.period = 1U;
445 outopts->period = (uint64_t)(unsigned long long)llv;
446 break;
447 case '0':
448 if (optarg)
449 while (*optarg == ' ' || *optarg == '\t')
450 ++optarg;
451 if (!optarg || !*optarg)
452 goto needarg;
453 llv = strtoll(optarg, &endp, 0);
454 if (endp != optarg)
455 while (*endp == ' ' || *endp == '\t')
456 ++endp;
457 if (endp == optarg || llv < 0)
458 goto badarg;
459 outopts->set.t0 = 1U;
460 outopts->t0 = (uint64_t)(unsigned long long)llv;
461 break;
462 case 'T':
463 if (optarg)
464 while (*optarg == ' ' || *optarg == '\t')
465 ++optarg;
466 if (!optarg || !*optarg)
467 goto needarg;
468 llv = strtoll(optarg, &endp, 0);
469 if (endp != optarg)
470 while (*endp == ' ' || *endp == '\t')
471 ++endp;
472 if (endp == optarg || llv < 0)
473 goto badarg;
474 outopts->set.testT = 1U;
475 outopts->testT = (uint64_t)(unsigned long long)llv;
476 break;
477 case 'D':
478 if (optarg)
479 while (*optarg == ' ' || *optarg == '\t')
480 ++optarg;
481 if (!optarg || !*optarg)
482 goto needarg;
483 llv = strtoll(optarg, &endp, 0);
484 if (endp != optarg)
485 while (*endp == ' ' || *endp == '\t')
486 ++endp;
487 if (endp == optarg || (llv != 6 && llv != 7 && llv != 8))
488 goto badarg;
489 outopts->digits = (unsigned)(unsigned long long)llv;
490 break;
491 case 'H':
492 if (optarg)
493 while (*optarg == ' ' || *optarg == '\t')
494 ++optarg;
495 if (!optarg || !*optarg)
496 goto needarg;
497 if (streqcase(optarg, "sha1"))
498 outopts->otphash = &otphash_table[otphash_sha1];
499 else if (streqcase(optarg, "sha256"))
500 outopts->otphash = &otphash_table[otphash_sha256];
501 else if (streqcase(optarg, "sha512"))
502 outopts->otphash = &otphash_table[otphash_sha512];
503 else
504 goto badarg;
505 break;
506 default:
507 edie(2, "%s: error: unknown option -%c (try -h)\n", appnm(), ch);
510 if (opt_h) {
511 if (opt_V)
512 outversion();
513 usage(0, opt_h > 1);
515 if (opt_V) {
516 outversion();
517 exit(0);
519 *argc -= optind;
520 *argv += optind;
521 if (*argc > 0)
522 usage(2, 0);
523 if (!outopts->sval && !outopts->b32val && !outopts->binval)
524 edie(2, "%s: error: at least one of -s, -3 or -b is required (try -h)\n",
525 appnm());
526 if ((outopts->sval ? 1 : 0) + (outopts->b32val ? 1 : 0) + (outopts->binval ? 1 : 0) != 1)
527 edie(2, "%s: error: at most one of -s, -3 or -b is allowed (try -h)\n",
528 appnm());
529 if (outopts->binval) {
530 size_t sz;
531 unsigned char *contents = readfile(outopts->binval, &sz, 1);
533 outopts->secret = contents;
534 outopts->secretSz = sz;
535 } else if (outopts->sval) {
536 size_t sz, sz2 = 0;
537 unsigned char *contents, *contents2, *p;
538 int freecontents = 0;
540 if (outopts->sval[0] == '@') {
541 contents = readfile(outopts->sval + 1, &sz, 0);
542 freecontents = 1;
543 } else {
544 contents = (unsigned char *)outopts->sval;
545 sz = strlen((char *)contents);
547 p = contents;
548 while (sz && isws(*p)) {
549 --sz;
550 ++p;
552 if (sz >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
553 sz -= 2;
554 p += 2;
556 contents2 = decodehex(p, sz, &sz2);
557 if (freecontents)
558 free(contents);
559 if (!contents2 || !sz2)
560 die("%s: error: invalid hexadecimal secret data\n", appnm());
561 outopts->secret = contents2;
562 outopts->secretSz = sz2;
563 } else /* outopts->b32val */ {
564 size_t sz, sz2 = 0;
565 unsigned char *contents, *contents2;
566 int freecontents = 0;
568 if (outopts->b32val[0] == '@') {
569 contents = readfile(outopts->b32val + 1, &sz, 0);
570 freecontents = 1;
571 } else {
572 contents = (unsigned char *)outopts->b32val;
573 sz = strlen((char *)contents);
575 contents2 = decodebase32(contents, sz, &sz2);
576 if (freecontents)
577 free(contents);
578 if (!contents2 || !sz2)
579 die("%s: error: invalid base 32 secret data\n", appnm());
580 outopts->secret = contents2;
581 outopts->secretSz = sz2;
583 if (outopts->set.counter) {
584 if (outopts->set.period || outopts->set.t0 || outopts->set.i ||
585 outopts->set.testT)
586 edie(2, "%s: error: -c is not compatible with -i, -p, -0 or -T\n",
587 appnm());
589 if (outopts->set.i && outopts->set.testT) {
590 fprintf(stderr, "%s: warning: ignoring -i because -T specified\n", appnm());
591 outopts->set.i = 0;
593 if (outopts->set.i && !isatty(STDOUT_FILENO)) {
594 fprintf(stderr, "%s: warning: ignoring -i because output is not a tty\n", appnm());
595 outopts->set.i = 0;
597 if (outopts->set.i) {
598 if (isrdtty(STDIN_FILENO))
599 outopts->iFileNo = STDIN_FILENO;
600 else if (isrdtty(STDERR_FILENO))
601 outopts->iFileNo = STDERR_FILENO;
602 else if (isrdtty(STDOUT_FILENO))
603 outopts->iFileNo = STDOUT_FILENO;
604 else {
605 fprintf(stderr, "%s: warning: ignoring -i because no input tty available\n", appnm());
606 outopts->set.i = 0;
609 if (outopts->set.testT && outopts->testT < outopts->t0)
610 edie(2, "%s: error: -T value (%llu) must be at least as big as the -0 value (%llu)\n",
611 appnm(), (unsigned long long)outopts->testT, (unsigned long long)outopts->t0);
612 if (!outopts->set.counter && !outopts->set.testT) {
613 uint64_t tnow = (uint64_t)time(NULL);
615 if (tnow < outopts->t0)
616 edie(2, "%s: error: time now (%llu) is less than time 0 (%llu)\n",
617 appnm(), (unsigned long long)tnow, (unsigned long long)outopts->t0);
621 static int
622 isws( unsigned c)
624 #define UCH(c) ((unsigned)(c))
625 return c == UCH(' ') || c == UCH('\t') || c == UCH('\n') ||
626 c == UCH('\r') || c == UCH('\f');
627 #undef UCH
630 static int
631 isrdtty(
632 int fd)
634 int acmode;
636 if (fd < 0 || fcntl(fd, F_GETFD) == -1 || !isatty(fd))
637 return 0;
638 acmode = fcntl(fd, F_GETFL);
639 if (acmode == -1)
640 return 0;
641 switch (acmode & O_ACCMODE) {
642 case O_RDONLY: return 1;
643 case O_RDWR: return 1;
644 default: return 0;
648 static void
649 flushinput(
650 int fd)
652 int acmode;
653 char discard[16];
655 acmode = fcntl(fd, F_GETFL);
656 if (acmode == -1)
657 return;
658 if (!(acmode & O_NONBLOCK)) {
659 if (fcntl(fd, F_SETFL, acmode | O_NONBLOCK) == -1)
660 return;
662 while (read(fd, discard, sizeof(discard)) > 0) {
663 /* loop */
665 if (!(acmode & O_NONBLOCK))
666 fcntl(fd, F_SETFL, acmode);
669 #define MAX_FILE_SZ 16384
670 #define MAX_DECODE_SZ (((MAX_FILE_SZ) + 1) / 2)
672 static unsigned char *
673 readfile(
674 const char *fn,
675 size_t *outsz,
676 int dobinary)
678 FILE *sfile;
679 unsigned char *data;
680 size_t rcnt;
681 int usingstdin = 0;
683 if (!fn || !outsz)
684 die("bad readfile args\n");
685 while (*fn == ' ' || *fn == '\t')
686 ++fn;
687 if (!*fn)
688 die("%s: error: empty file name is invalid\n", appnm());
689 if (fn[0] == '-' && !fn[1]) {
690 if (dobinary && isatty(STDIN_FILENO))
691 die("%s: error: refusing to read binary secret from isatty stdin\n",
692 appnm());
693 usingstdin = 1;
694 fn = "<stdin>";
696 data = (unsigned char *)malloc(MAX_FILE_SZ);
697 if (!data)
698 die("%s: error: unable to allocate memory block of size %u\n",
699 appnm(), MAX_FILE_SZ);
700 sfile = usingstdin ? stdin : fopen(fn, dobinary ? "rb" : "r");
701 if (!sfile)
702 die("%s: error: unable to open for reading file \"%s\"\n",
703 appnm(), fn);
704 rcnt = fread(data, 1, MAX_FILE_SZ, sfile);
705 if (rcnt >= MAX_FILE_SZ && !ferror(sfile) && !feof(sfile)) {
706 fclose(sfile);
707 die("%s: error: file too large (> %u bytes) \"%s\"\n", appnm(),
708 MAX_FILE_SZ, fn);
710 if (ferror(sfile)) {
711 fclose(sfile);
712 die("%s: error: unable to read file \"%s\"\n", appnm(), fn);
714 if (!usingstdin)
715 fclose(sfile);
716 if (!rcnt)
717 die("%s: error: empty file \"%s\"\n", appnm(), fn);
718 *outsz = rcnt;
719 return data;
722 static signed char hexdecode_table[96] = {
723 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 0x20 - 0x2F */
724 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, /* 0x30 - 0x3F */
725 -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 0x40 - 0x4F */
726 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 0x50 - 0x5F */
727 -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 0x60 - 0x6F */
728 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* 0x70 - 0x7F */
731 static unsigned char *
732 decodehex(
733 const void *data_,
734 size_t sz,
735 size_t *outszp)
737 const unsigned char *in = (unsigned char *)data_;
738 unsigned char *out, *p;
739 size_t outsz = 0;
740 int odd = 0;
741 unsigned char val = 0;
743 if (!in || !sz || !outszp)
744 return NULL;
745 out = (unsigned char *)malloc(MAX_DECODE_SZ);
746 if (!out)
747 die("%s: error: unable to allocate memory block of size %u\n",
748 appnm(), MAX_DECODE_SZ);
749 p = out;
750 do {
751 unsigned char c = *in++;
752 signed char d;
754 --sz;
755 if (isws(c))
756 continue;
757 if (c < 0x20 || c >= 0x80 || (d = hexdecode_table[c - 0x20]) < 0) {
758 free(out);
759 return NULL;
761 if (odd) {
762 val <<= 4;
763 val |= (unsigned char)d;
764 if (outsz >= MAX_DECODE_SZ)
765 die("%s: error: decoded hex size exceeds %u\n",
766 appnm(), MAX_DECODE_SZ);
767 *p++ = val;
768 ++outsz;
769 odd = 0;
770 } else {
771 val = (unsigned char)d;
772 odd = 1;
774 } while (sz);
775 if (odd) {
776 free(out);
777 return NULL;
779 *outszp = outsz;
780 return out;
783 static signed char b32decode_table[96] = {
784 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 0x20 - 0x2F */
785 -1,-1,26,27,28,29,30,31,-1,-1,-1,-1,-1,32,-1,-1, /* 0x30 - 0x3F */
786 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 0x40 - 0x4F */
787 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 0x50 - 0x5F */
788 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 0x60 - 0x6F */
789 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1 /* 0x70 - 0x7F */
792 static unsigned char *
793 decodebase32(
794 const void *data_,
795 size_t sz,
796 size_t *outszp)
798 const unsigned char *in = (unsigned char *)data_;
799 unsigned char *out, *p;
800 size_t outsz = 0;
801 unsigned bitcnt = 0;
802 unsigned bits = 0;
804 if (!in || !sz || !outszp)
805 return NULL;
806 out = (unsigned char *)malloc(MAX_DECODE_SZ);
807 if (!out)
808 die("%s: error: unable to allocate memory block of size %u\n",
809 appnm(), MAX_DECODE_SZ);
810 p = out;
811 do {
812 unsigned char c = *in++;
813 signed char d;
815 --sz;
816 if (isws(c))
817 continue;
818 if (c < 0x20 || c >= 0x80 || (d = b32decode_table[c - 0x20]) < 0) {
819 free(out);
820 return NULL;
822 if (d == 32) {
823 sz = 0;
824 } else {
825 bits <<= 5;
826 bits |= (unsigned char)d;
827 bitcnt += 5;
828 if (bitcnt >= 8) {
829 if (outsz >= MAX_DECODE_SZ)
830 die("%s: error: decoded base 32 size exceeds %u\n",
831 appnm(), MAX_DECODE_SZ);
832 *p++ = (unsigned char)(bits >> (bitcnt - 8));
833 ++outsz;
834 bits &= (1U << (bitcnt - 8)) - 1U;
835 bitcnt -= 8;
838 } while (sz);
839 if (bitcnt >= 5 || bits) {
840 free(out);
841 return NULL;
843 *outszp = outsz;
844 return out;
847 static unsigned char *
848 calchmac(
849 unsigned char *md,
850 const hmac_t *hfnc,
851 const void *k_,
852 size_t ksz,
853 const void *d_,
854 size_t dsz,
855 size_t *omdsz)
857 const unsigned char *k = (unsigned char *)k_;
858 const unsigned char *d = (unsigned char *)d_;
859 size_t idx;
860 unsigned char keydata[MAX_BLOCK_SIZE];
861 unsigned char hashdata[MAX_HASH_OUTPUT];
862 HMAC_CTX_t hctx;
864 if (!hfnc || !hfnc->outSize || !hfnc->blockSize || !hfnc->hashfunc ||
865 hfnc->outSize >= hfnc->blockSize)
866 return NULL;
867 if (!md || !k || !ksz || !d || !dsz || !omdsz)
868 return NULL;
869 if (hfnc->outSize > MAX_HASH_OUTPUT || hfnc->blockSize > MAX_BLOCK_SIZE)
870 return NULL;
871 if (ksz > hfnc->blockSize) {
872 (*hfnc->hashfunc)(k, ksz, keydata);
873 memset(keydata + hfnc->outSize, 0, hfnc->blockSize - hfnc->outSize);
874 } else {
875 memcpy(keydata, k, ksz);
876 if (ksz < hfnc->blockSize)
877 memset(keydata + ksz, 0, hfnc->blockSize - ksz);
879 for (idx = 0; idx < hfnc->blockSize; ++idx)
880 keydata[idx] ^= 0x36;
881 if (!(*hfnc->hashinitfunc)(&hctx))
882 die("hash init failed\n");
883 if (!(*hfnc->hashupdatefunc)(&hctx, keydata, hfnc->blockSize))
884 die("hash update failed\n");
885 if (!(*hfnc->hashupdatefunc)(&hctx, d, dsz))
886 die("hash update failed\n");
887 if (!(*hfnc->hashfinalfunc)(hashdata, &hctx))
888 die("hash final failed\n");
889 for (idx = 0; idx < hfnc->blockSize; ++idx)
890 keydata[idx] ^= (0x36 ^ 0x5C);
891 if (!(*hfnc->hashinitfunc)(&hctx))
892 die("hash init failed\n");
893 if (!(*hfnc->hashupdatefunc)(&hctx, keydata, hfnc->blockSize))
894 die("hash update failed\n");
895 if (!(*hfnc->hashupdatefunc)(&hctx, hashdata, hfnc->outSize))
896 die("hash update failed\n");
897 if (!(*hfnc->hashfinalfunc)(md, &hctx))
898 die("hash final failed\n");
899 *omdsz = hfnc->outSize;
900 return md;
903 static void
904 vedie( int ec,
905 const char *fmt,
906 va_list args)
908 vfprintf(stderr, fmt, args);
909 exit(ec);
912 static void
913 edie( int ec,
914 const char *fmt,
915 ...)
917 va_list args;
919 va_start(args, fmt);
920 vedie(ec, fmt, args);
921 va_end(args);
924 static void
925 die( const char *fmt,
926 ...)
928 va_list args;
930 va_start(args, fmt);
931 vedie(255, fmt, args);
932 va_end(args);