3 * Generate and validate cryptographic cookies
5 * (c) 1999 Mark Wooding
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
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 General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with Catacomb; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 /*----- Header files ------------------------------------------------------*/
29 #define _FILE_OFFSET_BITS 64
39 #include <mLib/base64.h>
40 #include <mLib/bits.h>
41 #include <mLib/dstr.h>
42 #include <mLib/mdwopt.h>
43 #include <mLib/quis.h>
44 #include <mLib/report.h>
53 /*----- Handy global state ------------------------------------------------*/
55 static const char *keyfile = "keyring";
57 /*----- Cookie format -----------------------------------------------------*/
59 /* --- Cookie header structure (unpacked) --- */
61 typedef struct cookie {
66 /* --- Size of a cookie header (packed) --- */
68 #define COOKIE_SZ (4 + 8)
70 /* --- @COOKIE_PACK@ --- *
72 * Arguments: @p@ = pointer to destination buffer
73 * @c@ = pointer to source cookie header block
75 * Use: Packs a cookie header into an octet buffer in a machine-
79 #define COOKIE_PACK(p, c) do { \
80 octet *_p = (octet *)(p); \
81 const cookie *_c = (c); \
82 STORE32(_p + 0, _c->k); \
83 STORE32(_p + 4, ((_c->exp & ~MASK32) >> 16) >> 16); \
84 STORE32(_p + 8, _c->exp); \
87 /* --- @COOKIE_UNPACK@ --- *
89 * Arguments: @c@ = pointer to destination cookie header
90 * @p@ = pointer to source buffer
92 * Use: Unpacks a cookie header from an octet buffer into a
93 * machine-specific but comprehensible structure.
96 #define COOKIE_UNPACK(c, p) do { \
98 const octet *_p = (const octet *)(p); \
99 _c->k = LOAD32(_p + 0); \
100 _c->exp = ((time_t)(((LOAD32(_p + 4) << 16) << 16) & ~MASK32) | \
101 (time_t)LOAD32(_p + 8)); \
104 /*----- Useful shared functions -------------------------------------------*/
106 /* --- @doopen@ --- *
108 * Arguments: @key_file *f@ = pointer to key file block
109 * @unsigned how@ = method to open file with
113 * Use: Opens a key file and handles errors by panicking
117 static void doopen(key_file *f, unsigned how)
119 if (key_open(f, keyfile, how, key_moan, 0)) {
120 die(EXIT_FAILURE, "couldn't open file `%s': %s",
121 keyfile, strerror(errno));
125 /* --- @doclose@ --- *
127 * Arguments: @key_file *f@ = pointer to key file block
131 * Use: Closes a key file and handles errors by panicking
135 static void doclose(key_file *f)
137 switch (key_close(f)) {
139 die(EXIT_FAILURE, "couldn't write file `%s': %s",
140 keyfile, strerror(errno));
142 die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
143 keyfile, strerror(errno));
147 /* --- @getmac@ --- *
149 * Arguments: @key *k@ = key to use
150 * @const char *app@ = application name
152 * Returns: The MAC to use.
154 * Use: Finds the right MAC for the given key.
157 static gmac *getmac(key *k, const char *app)
174 /* --- Pick out the right MAC --- */
177 if ((q = key_getattr(0, k, "mac")) != 0) {
180 } else if (strncmp(k->type, app, n) == 0 && k->type[n] == '-') {
181 dstr_puts(&d, k->type);
184 die(EXIT_FAILURE, "no MAC algorithm for key `%s'", t.buf);
185 if ((cm = gmac_byname(p)) == 0) {
186 die(EXIT_FAILURE, "MAC algorithm `%s' not found in key `%s'",
190 /* --- Unlock the key --- */
194 if ((e = key_unpack(&kp, k->k, &t)) != 0) {
195 die(EXIT_FAILURE, "error unpacking key `%s': %s",
196 t.buf, key_strerror(e));
199 /* --- Make the MAC object --- */
201 if (keysz(kb.sz, cm->keysz) != kb.sz)
202 die(EXIT_FAILURE, "key %s has bad length (%lu) for MAC %s",
203 t.buf, (unsigned long)kb.sz, cm->name);
204 m = cm->key(kb.k, kb.sz);
209 /*----- Command implementation --------------------------------------------*/
211 /* --- @cmd_gen@ --- */
213 static int cmd_gen(int argc, char *argv[])
219 const char *tag = "cookie";
221 cookie c = { 0, KEXP_EXPIRE };
226 octet buf[COOKIE_SZ];
229 /* --- Various useful flag bits --- */
233 /* --- Parse options for the subcommand --- */
236 static struct option opt[] = {
237 { "bits", OPTF_ARGREQ, 0, 'b' },
238 { "expire", OPTF_ARGREQ, 0, 'e' },
239 { "key", OPTF_ARGREQ, 0, 'k' },
242 int i = mdwopt(argc, argv, "+b:e:i:t:", opt, 0, 0, 0);
246 /* --- Handle the various options --- */
250 /* --- Fetch a size in bits --- */
253 if (!(bits = atoi(optarg)) || bits % 8)
254 die(EXIT_FAILURE, "bad number of bits: `%s'", optarg);
257 /* --- Fetch an expiry time --- */
260 if (strcmp(optarg, "forever") == 0)
261 c.exp = KEXP_FOREVER;
262 else if ((c.exp = get_date(optarg, 0)) == -1)
263 die(EXIT_FAILURE, "bad expiry date: `%s'", optarg);
266 /* --- Fetch a key type --- */
272 /* --- Other things are bogus --- */
280 /* --- Various sorts of bogosity --- */
282 if (fl & f_bogus || optind + 1 < argc)
284 "Usage: generate [-b BITS] [-e TIME] [-k TAG] [DATA]");
286 /* --- Choose a default expiry time --- */
288 if (c.exp == KEXP_EXPIRE)
289 c.exp = time(0) + 7 * 24 * 60 * 60;
291 /* --- Open the key file and get the key --- */
293 doopen(&f, KOPEN_WRITE);
294 if ((k = key_bytag(&f, tag)) == 0) {
295 die(EXIT_FAILURE, "no key with tag `%s' in keyring `%s'",
300 if ((err = key_used(&f, k, c.exp)) != 0)
301 die(EXIT_FAILURE, "can't generate cookie: %s", key_strerror(err));
302 m = getmac(k, "cookie");
303 if (bits/8 > GM_CLASS(m)->hashsz) {
304 die(EXIT_FAILURE, "inapproriate bit length for `%s' MACs",
308 /* --- Store and MAC the cookie --- */
310 COOKIE_PACK(buf, &c);
313 GH_HASH(h, buf, sizeof(buf));
315 GH_HASH(h, argv[optind], strlen(argv[optind]));
318 /* --- Encode and emit the finished cookie --- */
322 base64_encode(&b, buf, sizeof(buf), &d);
323 base64_encode(&b, t, bits/8, &d);
324 base64_encode(&b, 0, 0, &d);
337 /* --- @cmd_verify@ --- */
339 static int cmd_verify(int argc, char *argv[])
344 int bits = -1, minbits = 32;
353 time_t now = time(0);
355 /* --- Various useful flag bits --- */
361 /* --- Parse options for the subcommand --- */
364 static struct option opt[] = {
365 { "bits", OPTF_ARGREQ, 0, 'b' },
366 { "min-bits", OPTF_ARGREQ, 0, 'm' },
367 { "forever", 0, 0, 'f' },
368 { "quiet", 0, 0, 'q' },
369 { "verbose", 0, 0, 'v' },
370 { "utc", 0, 0, 'u' },
373 int i = mdwopt(argc, argv, "+b:m:fqvu", opt, 0, 0, 0);
377 /* --- Handle the various options --- */
381 /* --- Fetch a size in bits --- */
384 if (!(bits = atoi(optarg)) || bits % 8)
385 die(EXIT_FAILURE, "bad number of bits: `%s'", optarg);
388 if (!(minbits = atoi(optarg)) || minbits % 8)
389 die(EXIT_FAILURE, "bad number of bits: `%s'", optarg);
392 /* --- Miscellaneous flags --- */
407 /* --- Other things are bogus --- */
415 /* --- Various sorts of bogosity --- */
417 if (fl & f_bogus || optind == argc || optind + 2 < argc) {
419 "Usage: verify [-fuqv] [-b BITS] [-m BITS] COOKIE [DATA]");
421 doopen(&f, KOPEN_READ);
423 /* --- Decode the base64 wrapping --- */
426 base64_decode(&b, argv[optind], strlen(argv[optind]), &d);
427 base64_decode(&b, 0, 0, &d);
429 if (d.len < COOKIE_SZ + 1) {
430 if (v) printf("FAIL cookie too small\n");
434 /* --- Extract the relevant details --- */
436 COOKIE_UNPACK(&c, d.buf);
440 if (c.exp == KEXP_FOREVER)
441 strcpy(buf, "forever");
448 fmt = "%Y-%m-%d %H:%M:%S UTC";
450 tm = localtime(&c.exp);
451 fmt = "%Y-%m-%d %H:%M:%S %Z";
453 strftime(buf, sizeof(buf), fmt, tm);
455 printf("INFO keyid = %08lx; expiry = %s\n", (unsigned long)c.k, buf);
458 /* --- Check the authentication token width --- */
460 cbits = (d.len - COOKIE_SZ) * 8;
461 if (v > 2) printf("INFO authentication token width = %i bits\n", cbits);
463 if (cbits < minbits) {
464 if (v) printf("FAIL authentication token too narrow\n");
469 if (v) printf("FAIL authentication token width doesn't match\n");
473 /* --- Get the key --- */
475 if ((k = key_byid(&f, c.k)) == 0) {
476 if (v) printf("FAIL keyid %08lx unavailable\n", (unsigned long)c.k);
480 /* --- Check that the cookie authenticates OK --- */
482 m = getmac(k, "cookie");
484 GH_HASH(h, d.buf, COOKIE_SZ);
485 if (argv[optind + 1])
486 GH_HASH(h, argv[optind + 1], strlen(argv[optind + 1]));
489 if (!ct_memeq(t, d.buf + COOKIE_SZ, cbits / 8)) {
490 if (v) printf("FAIL bad authentication token\n");
494 /* --- See whether the cookie has expired --- */
496 if (c.exp == KEXP_FOREVER) {
497 if (!(fl & f_forever)) {
498 if (v) printf("FAIL forever cookies not allowed\n");
501 if (k->exp != KEXP_FOREVER) {
502 if (v) printf("FAIL cookie lasts forever but key will expire\n");
505 } else if (c.exp < now) {
506 if (v) printf("FAIL cookie has expired\n");
510 if (v) printf("OK\n");
527 /*----- Main command table ------------------------------------------------*/
529 static int cmd_help(int, char **);
533 listtab[i].name, listtab[i].name) \
534 LI("Message authentication algorithms", mac, \
535 gmactab[i], gmactab[i]->name)
537 MAKELISTTAB(listtab, LISTS)
539 static int cmd_show(int argc, char *argv[])
541 return (displaylists(listtab, argv + 1));
544 static cmd cmds[] = {
545 { "help", cmd_help, "help [COMMAND...]" },
546 { "show", cmd_show, "show [ITEM...]" },
547 { "generate", cmd_gen,
548 "generate [-b BITS] [-e TIME] [-k TAG] [DATA]", "\
551 -b, --bits=N Use an N-bit token in the cookie.\n\
552 -e, --expire=TIME Make the cookie expire after TIME.\n\
553 -k, --key=TAG Use key TAG to create the token.\n\
555 { "verify", cmd_verify,
556 "verify [-fuqv] [-b BITS] [-m BITS] COOKIE [DATA]", "\
559 -b, --bits=N Accept tokens exactly N bits long only.\n\
560 -m, --min-bits=N Accept tokens N bits long or more.\n\
561 -f, --forever Accept cookies which never expire.\n\
562 -u, --utc Output cookie expiry dates in UTC.\n\
563 -q, --quiet Produce less output while checking cookies.\n\
564 -v, --verbose Produce more output while checking cookies.\n\
569 static int cmd_help(int argc, char *argv[])
571 sc_help(cmds, stdout, argv + 1);
575 /*----- Main code ---------------------------------------------------------*/
577 /* --- Helpful GNUy functions --- */
579 static void usage(FILE *fp)
581 fprintf(fp, "Usage: %s [-k KEYRING] COMMAND [ARGS]\n", QUIS);
584 void version(FILE *fp)
586 fprintf(fp, "%s, Catacomb version " VERSION "\n", QUIS);
589 void help_global(FILE *fp)
593 Generates and validates cryptographic cookies. Command line options\n\
596 -h, --help [COMMAND] Display this help text (or help for COMMAND).\n\
597 -v, --version Display version number.\n\
598 -u, --usage Display short usage summary.\n\
600 -k, --key-file=FILE Read and write keys in FILE.\n",
606 * Arguments: @int argc@ = number of command line arguments
607 * @char *argv[]@ = array of arguments
609 * Returns: Zero if OK, nonzero if not.
611 * Use: Generates and validates cryptographic cookies.
614 int main(int argc, char *argv[])
621 /* --- Initialize the library --- */
626 /* --- Options parsing --- */
629 static struct option opt[] = {
631 /* --- Standard GNUy help options --- */
633 { "help", 0, 0, 'h' },
634 { "version", 0, 0, 'v' },
635 { "usage", 0, 0, 'u' },
637 /* --- Actual relevant options --- */
639 { "keyring", OPTF_ARGREQ, 0, 'k' },
641 /* --- Magic terminator --- */
645 int i = mdwopt(argc, argv, "+hvu k:", opt, 0, 0, 0);
651 /* --- Helpful GNUs --- */
660 sc_help(cmds, stdout, argv + optind);
663 /* --- Real genuine useful options --- */
669 /* --- Bogus things --- */
677 if ((f & f_bogus) || optind == argc) {
682 /* --- Dispatch to appropriate command handler --- */
687 return (findcmd(cmds, argv[0])->cmd(argc, argv));
693 /*----- That's all, folks -------------------------------------------------*/