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 & ~(unsigned long)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) & \
101 ~(unsigned long)MASK32) | \
102 (time_t)LOAD32(_p + 8)); \
105 /*----- Useful shared functions -------------------------------------------*/
107 /* --- @doopen@ --- *
109 * Arguments: @key_file *f@ = pointer to key file block
110 * @unsigned how@ = method to open file with
114 * Use: Opens a key file and handles errors by panicking
118 static void doopen(key_file
*f
, unsigned how
)
120 if (key_open(f
, keyfile
, how
, key_moan
, 0)) {
121 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
122 keyfile
, strerror(errno
));
126 /* --- @doclose@ --- *
128 * Arguments: @key_file *f@ = pointer to key file block
132 * Use: Closes a key file and handles errors by panicking
136 static void doclose(key_file
*f
)
138 switch (key_close(f
)) {
140 die(EXIT_FAILURE
, "couldn't write file `%s': %s",
141 keyfile
, strerror(errno
));
143 die(EXIT_FAILURE
, "keyring file `%s' broken: %s (repair manually)",
144 keyfile
, strerror(errno
));
148 /* --- @getmac@ --- *
150 * Arguments: @key *k@ = key to use
151 * @const char *app@ = application name
153 * Returns: The MAC to use.
155 * Use: Finds the right MAC for the given key.
158 static gmac
*getmac(key
*k
, const char *app
)
175 /* --- Pick out the right MAC --- */
178 if ((q
= key_getattr(0, k
, "mac")) != 0) {
181 } else if (strncmp(k
->type
, app
, n
) == 0 && k
->type
[n
] == '-') {
182 dstr_puts(&d
, k
->type
);
185 die(EXIT_FAILURE
, "no MAC algorithm for key `%s'", t
.buf
);
186 if ((cm
= gmac_byname(p
)) == 0) {
187 die(EXIT_FAILURE
, "MAC algorithm `%s' not found in key `%s'",
191 /* --- Unlock the key --- */
195 if ((e
= key_unpack(&kp
, k
->k
, &t
)) != 0) {
196 die(EXIT_FAILURE
, "error unpacking key `%s': %s",
197 t
.buf
, key_strerror(e
));
200 /* --- Make the MAC object --- */
202 if (keysz(kb
.sz
, cm
->keysz
) != kb
.sz
)
203 die(EXIT_FAILURE
, "key %s has bad length (%lu) for MAC %s",
204 t
.buf
, (unsigned long)kb
.sz
, cm
->name
);
205 m
= cm
->key(kb
.k
, kb
.sz
);
210 /*----- Command implementation --------------------------------------------*/
212 /* --- @cmd_gen@ --- */
214 static int cmd_gen(int argc
, char *argv
[])
220 const char *tag
= "cookie";
222 cookie c
= { 0, KEXP_EXPIRE
};
227 octet buf
[COOKIE_SZ
];
230 /* --- Various useful flag bits --- */
234 /* --- Parse options for the subcommand --- */
237 static struct option opt
[] = {
238 { "bits", OPTF_ARGREQ
, 0, 'b' },
239 { "expire", OPTF_ARGREQ
, 0, 'e' },
240 { "key", OPTF_ARGREQ
, 0, 'k' },
243 int i
= mdwopt(argc
, argv
, "+b:e:i:t:", opt
, 0, 0, 0);
247 /* --- Handle the various options --- */
251 /* --- Fetch a size in bits --- */
254 if (!(bits
= atoi(optarg
)) || bits
% 8)
255 die(EXIT_FAILURE
, "bad number of bits: `%s'", optarg
);
258 /* --- Fetch an expiry time --- */
261 if (strcmp(optarg
, "forever") == 0)
262 c
.exp
= KEXP_FOREVER
;
263 else if ((c
.exp
= get_date(optarg
, 0)) == -1)
264 die(EXIT_FAILURE
, "bad expiry date: `%s'", optarg
);
267 /* --- Fetch a key type --- */
273 /* --- Other things are bogus --- */
281 /* --- Various sorts of bogosity --- */
283 if (fl
& f_bogus
|| optind
+ 1 < argc
)
285 "Usage: generate [-b BITS] [-e TIME] [-k TAG] [DATA]");
287 /* --- Choose a default expiry time --- */
289 if (c
.exp
== KEXP_EXPIRE
)
290 c
.exp
= time(0) + 7 * 24 * 60 * 60;
292 /* --- Open the key file and get the key --- */
294 doopen(&f
, KOPEN_WRITE
);
295 if ((k
= key_bytag(&f
, tag
)) == 0) {
296 die(EXIT_FAILURE
, "no key with tag `%s' in keyring `%s'",
301 if ((err
= key_used(&f
, k
, c
.exp
)) != 0)
302 die(EXIT_FAILURE
, "can't generate cookie: %s", key_strerror(err
));
303 m
= getmac(k
, "cookie");
304 if (bits
/8 > GM_CLASS(m
)->hashsz
) {
305 die(EXIT_FAILURE
, "inapproriate bit length for `%s' MACs",
309 /* --- Store and MAC the cookie --- */
311 COOKIE_PACK(buf
, &c
);
314 GH_HASH(h
, buf
, sizeof(buf
));
316 GH_HASH(h
, argv
[optind
], strlen(argv
[optind
]));
319 /* --- Encode and emit the finished cookie --- */
323 base64_encode(&b
, buf
, sizeof(buf
), &d
);
324 base64_encode(&b
, t
, bits
/8, &d
);
325 base64_encode(&b
, 0, 0, &d
);
338 /* --- @cmd_verify@ --- */
340 static int cmd_verify(int argc
, char *argv
[])
345 int bits
= -1, minbits
= 32;
354 time_t now
= time(0);
356 /* --- Various useful flag bits --- */
362 /* --- Parse options for the subcommand --- */
365 static struct option opt
[] = {
366 { "bits", OPTF_ARGREQ
, 0, 'b' },
367 { "min-bits", OPTF_ARGREQ
, 0, 'm' },
368 { "forever", 0, 0, 'f' },
369 { "quiet", 0, 0, 'q' },
370 { "verbose", 0, 0, 'v' },
371 { "utc", 0, 0, 'u' },
374 int i
= mdwopt(argc
, argv
, "+b:m:fqvu", opt
, 0, 0, 0);
378 /* --- Handle the various options --- */
382 /* --- Fetch a size in bits --- */
385 if (!(bits
= atoi(optarg
)) || bits
% 8)
386 die(EXIT_FAILURE
, "bad number of bits: `%s'", optarg
);
389 if (!(minbits
= atoi(optarg
)) || minbits
% 8)
390 die(EXIT_FAILURE
, "bad number of bits: `%s'", optarg
);
393 /* --- Miscellaneous flags --- */
408 /* --- Other things are bogus --- */
416 /* --- Various sorts of bogosity --- */
418 if (fl
& f_bogus
|| optind
== argc
|| optind
+ 2 < argc
) {
420 "Usage: verify [-fuqv] [-b BITS] [-m BITS] COOKIE [DATA]");
422 doopen(&f
, KOPEN_READ
);
424 /* --- Decode the base64 wrapping --- */
427 base64_decode(&b
, argv
[optind
], strlen(argv
[optind
]), &d
);
428 base64_decode(&b
, 0, 0, &d
);
430 if (d
.len
< COOKIE_SZ
+ 1) {
431 if (v
) printf("FAIL cookie too small\n");
435 /* --- Extract the relevant details --- */
437 COOKIE_UNPACK(&c
, d
.buf
);
441 if (c
.exp
== KEXP_FOREVER
)
442 strcpy(buf
, "forever");
449 fmt
= "%Y-%m-%d %H:%M:%S UTC";
451 tm
= localtime(&c
.exp
);
452 fmt
= "%Y-%m-%d %H:%M:%S %Z";
454 strftime(buf
, sizeof(buf
), fmt
, tm
);
456 printf("INFO keyid = %08lx; expiry = %s\n", (unsigned long)c
.k
, buf
);
459 /* --- Check the authentication token width --- */
461 cbits
= (d
.len
- COOKIE_SZ
) * 8;
462 if (v
> 2) printf("INFO authentication token width = %i bits\n", cbits
);
464 if (cbits
< minbits
) {
465 if (v
) printf("FAIL authentication token too narrow\n");
470 if (v
) printf("FAIL authentication token width doesn't match\n");
474 /* --- Get the key --- */
476 if ((k
= key_byid(&f
, c
.k
)) == 0) {
477 if (v
) printf("FAIL keyid %08lx unavailable\n", (unsigned long)c
.k
);
481 /* --- Check that the cookie authenticates OK --- */
483 m
= getmac(k
, "cookie");
485 GH_HASH(h
, d
.buf
, COOKIE_SZ
);
486 if (argv
[optind
+ 1])
487 GH_HASH(h
, argv
[optind
+ 1], strlen(argv
[optind
+ 1]));
490 if (!ct_memeq(t
, d
.buf
+ COOKIE_SZ
, cbits
/ 8)) {
491 if (v
) printf("FAIL bad authentication token\n");
495 /* --- See whether the cookie has expired --- */
497 if (c
.exp
== KEXP_FOREVER
) {
498 if (!(fl
& f_forever
)) {
499 if (v
) printf("FAIL forever cookies not allowed\n");
502 if (k
->exp
!= KEXP_FOREVER
) {
503 if (v
) printf("FAIL cookie lasts forever but key will expire\n");
506 } else if (c
.exp
< now
) {
507 if (v
) printf("FAIL cookie has expired\n");
511 if (v
) printf("OK\n");
528 /*----- Main command table ------------------------------------------------*/
530 static int cmd_help(int, char **);
534 listtab[i].name, listtab[i].name) \
535 LI("Message authentication algorithms", mac, \
536 gmactab[i], gmactab[i]->name)
538 MAKELISTTAB(listtab
, LISTS
)
540 static int cmd_show(int argc
, char *argv
[])
542 return (displaylists(listtab
, argv
+ 1));
545 static cmd cmds
[] = {
546 { "help", cmd_help
, "help [COMMAND...]" },
547 { "show", cmd_show
, "show [ITEM...]" },
548 { "generate", cmd_gen
,
549 "generate [-b BITS] [-e TIME] [-k TAG] [DATA]", "\
552 -b, --bits=N Use an N-bit token in the cookie.\n\
553 -e, --expire=TIME Make the cookie expire after TIME.\n\
554 -k, --key=TAG Use key TAG to create the token.\n\
556 { "verify", cmd_verify
,
557 "verify [-fuqv] [-b BITS] [-m BITS] COOKIE [DATA]", "\
560 -b, --bits=N Accept tokens exactly N bits long only.\n\
561 -m, --min-bits=N Accept tokens N bits long or more.\n\
562 -f, --forever Accept cookies which never expire.\n\
563 -u, --utc Output cookie expiry dates in UTC.\n\
564 -q, --quiet Produce less output while checking cookies.\n\
565 -v, --verbose Produce more output while checking cookies.\n\
570 static int cmd_help(int argc
, char *argv
[])
572 sc_help(cmds
, stdout
, argv
+ 1);
576 /*----- Main code ---------------------------------------------------------*/
578 /* --- Helpful GNUy functions --- */
580 static void usage(FILE *fp
)
582 fprintf(fp
, "Usage: %s [-k KEYRING] COMMAND [ARGS]\n", QUIS
);
585 void version(FILE *fp
)
587 fprintf(fp
, "%s, Catacomb version " VERSION
"\n", QUIS
);
590 void help_global(FILE *fp
)
594 Generates and validates cryptographic cookies. Command line options\n\
597 -h, --help [COMMAND] Display this help text (or help for COMMAND).\n\
598 -v, --version Display version number.\n\
599 -u, --usage Display short usage summary.\n\
601 -k, --key-file=FILE Read and write keys in FILE.\n",
607 * Arguments: @int argc@ = number of command line arguments
608 * @char *argv[]@ = array of arguments
610 * Returns: Zero if OK, nonzero if not.
612 * Use: Generates and validates cryptographic cookies.
615 int main(int argc
, char *argv
[])
622 /* --- Initialize the library --- */
627 /* --- Options parsing --- */
630 static struct option opt
[] = {
632 /* --- Standard GNUy help options --- */
634 { "help", 0, 0, 'h' },
635 { "version", 0, 0, 'v' },
636 { "usage", 0, 0, 'u' },
638 /* --- Actual relevant options --- */
640 { "keyring", OPTF_ARGREQ
, 0, 'k' },
642 /* --- Magic terminator --- */
646 int i
= mdwopt(argc
, argv
, "+hvu k:", opt
, 0, 0, 0);
652 /* --- Helpful GNUs --- */
661 sc_help(cmds
, stdout
, argv
+ optind
);
664 /* --- Real genuine useful options --- */
670 /* --- Bogus things --- */
678 if ((f
& f_bogus
) || optind
== argc
) {
683 /* --- Dispatch to appropriate command handler --- */
688 return (findcmd(cmds
, argv
[0])->cmd(argc
, argv
));
694 /*----- That's all, folks -------------------------------------------------*/