3 * $Id: keyutil.c,v 1.7 2000/07/01 11:18:51 mdw Exp $
5 * Simple key manager program
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of Catacomb.
14 * Catacomb is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
19 * Catacomb 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 Library General Public License for more details.
24 * You should have received a copy of the GNU Library General Public
25 * License along with Catacomb; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
30 /*----- Revision history --------------------------------------------------*
33 * Revision 1.7 2000/07/01 11:18:51 mdw
34 * Use new interfaces for key manipulation.
36 * Revision 1.6 2000/06/17 11:28:22 mdw
37 * Use secure memory interface from MP library. `rand_getgood' is
40 * Revision 1.5 2000/02/12 18:21:03 mdw
41 * Overhaul of key management (again).
43 * Revision 1.4 1999/12/22 15:48:10 mdw
44 * Track new key-management changes. Support new key generation
47 * Revision 1.3 1999/11/02 15:23:24 mdw
48 * Fix newlines in keyring list.
50 * Revision 1.2 1999/10/15 21:05:28 mdw
51 * In `key list', show timezone for local times, and support `-u' option
54 * Revision 1.1 1999/09/03 08:41:12 mdw
59 /*----- Header files ------------------------------------------------------*/
69 #include <mLib/base64.h>
70 #include <mLib/mdwopt.h>
71 #include <mLib/quis.h>
72 #include <mLib/report.h>
91 /*----- Handy global state ------------------------------------------------*/
93 static const char *keyfile = "keyring";
95 /*----- Useful shared functions -------------------------------------------*/
99 * Arguments: @key_file *f@ = pointer to key file block
100 * @unsigned how@ = method to open file with
104 * Use: Opens a key file and handles errors by panicking
108 static void doopen(key_file *f, unsigned how)
110 if (key_open(f, keyfile, how, key_moan, 0))
111 die(1, "couldn't open keyring `%s': %s", keyfile, strerror(errno));
114 /* --- @doclose@ --- *
116 * Arguments: @key_file *f@ = pointer to key file block
120 * Use: Closes a key file and handles errors by panicking
124 static void doclose(key_file *f)
126 switch (key_close(f)) {
128 die(EXIT_FAILURE, "couldn't write file `%s': %s",
129 keyfile, strerror(errno));
131 die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
132 keyfile, strerror(errno));
136 /* --- @setattr@ --- *
138 * Arguments: @key_file *f@ = pointer to key file block
139 * @key *k@ = pointer to key block
140 * @char *v[]@ = array of assignments (overwritten!)
144 * Use: Applies the attribute assignments to the key.
147 static void setattr(key_file *f, key *k, char *v[])
152 size_t eq = strcspn(p, "=");
154 moan("invalid assignment: `%s'", p);
157 if ((err = key_putattr(f, k, *v, *p ? p : 0)) != 0)
158 die(EXIT_FAILURE, "couldn't set attributes: %s", key_strerror(err));
163 /*----- Key generation ----------------------------------------------------*/
165 /* --- Key generation parameters --- */
167 typedef struct keyopts {
168 key_file *kf; /* Pointer to key file */
169 key *k; /* Pointer to the actual key */
170 dstr tag; /* Full tag name for the key */
171 unsigned f; /* Flags for the new key */
172 unsigned bits, qbits; /* Bit length for the new key */
173 key *p; /* Parameters key-data */
177 f_bogus = 1, /* Error in parsing */
178 f_lock = 2, /* Passphrase-lock private key */
179 f_quiet = 4 /* Don't show a progress indicator */
182 /* --- @dolock@ --- *
184 * Arguments: @keyopts *k@ = key generation options
185 * @key_data *kd@ = pointer to key data to lock
186 * @const char *t@ = tag suffix or null
190 * Use: Does passphrase locking on new keys.
193 static void dolock(keyopts *k, key_data *kd, const char *t)
195 if (!(k->f & f_lock))
198 dstr_putf(&k->tag, ".%s", t);
199 if (key_plock(k->tag.buf, kd, kd))
200 die(EXIT_FAILURE, "couldn't lock key");
205 * Arguments: @key_data *kd@ = pointer to parent key block
206 * @const char *tag@ = pointer to tag string
207 * @mp *m@ = integer to store
208 * @unsigned f@ = flags to set
212 * Use: Sets a multiprecision integer subkey.
215 static void mpkey(key_data *kd, const char *tag, mp *m, unsigned f)
217 key_data *kkd = key_structcreate(kd, tag);
222 /* --- @copyparam@ --- *
224 * Arguments: @keyopts *k@ = pointer to key options
225 * @const char **pp@ = checklist of parameters
227 * Returns: Nonzero if parameters copied; zero if you have to generate
230 * Use: Copies parameters from a source key to the current one.
233 static int copyparam(keyopts *k, const char **pp)
237 /* --- Quick check if no parameters supplied --- */
242 /* --- Run through the checklist --- */
245 key_data *kd = key_structfind(&k->p->k, *pp);
247 die(EXIT_FAILURE, "bad parameter key: parameter `%s' not found", *pp);
248 if ((kd->e & KF_CATMASK) != KCAT_SHARE)
249 die(EXIT_FAILURE, "bad parameter key: subkey `%s' is not shared", *pp);
253 /* --- Copy over the parameters --- */
257 if (!key_copy(&k->k->k, &k->p->k, &kf))
258 die(EXIT_FAILURE, "unexpected failure while copying parameters");
264 * Arguments: @key_data *k@ = pointer to key data block
265 * @const char *tag@ = tag string to use
267 * Returns: Pointer to multiprecision integer key item.
269 * Use: Fetches an MP key component.
272 static mp *getmp(key_data *k, const char *tag)
274 k = key_structfind(k, tag);
276 die(EXIT_FAILURE, "unexpected failure looking up subkey `%s'", tag);
277 if ((k->e & KF_ENCMASK) != KENC_MP)
278 die(EXIT_FAILURE, "subkey `%s' has an incompatible type");
282 /* --- @keyrand@ --- *
284 * Arguments: @key_file *kf@ = pointer to key file
285 * @const char *id@ = pointer to key id (or null)
289 * Use: Keys the random number generator.
292 static void keyrand(key_file *kf, const char *id)
296 /* --- Find the key --- */
299 if ((k = key_bytag(kf, id)) == 0)
300 die(EXIT_FAILURE, "key `%s' not found", id);
302 k = key_bytype(kf, "catacomb-rand");
305 key_data *kd = &k->k, kkd;
308 switch (kd->e & KF_ENCMASK) {
314 if (key_punlock(d.buf, kd, &kkd))
315 die(EXIT_FAILURE, "error unlocking key `%s'", d.buf);
322 die(EXIT_FAILURE, "bad encoding type for key `%s'", d.buf);
326 /* --- Key the generator --- */
328 rand_key(RAND_GLOBAL, kd->u.k.k, kd->u.k.sz);
334 /* --- Key generation algorithms --- */
336 static void alg_binary(keyopts *k)
345 die(EXIT_FAILURE, "no shared parameters for binary keys");
347 sz = (k->bits + 7) >> 3;
349 m = (1 << (((k->bits - 1) & 7) + 1)) - 1;
350 rand_get(RAND_GLOBAL, p, sz);
352 key_binary(&k->k->k, p, sz);
353 k->k->k.e |= KCAT_SYMM | KF_BURN;
356 dolock(k, &k->k->k, 0);
359 static void alg_des(keyopts *k)
368 die(EXIT_FAILURE, "no shared parameters for DES keys");
369 if (k->bits % 56 || k->bits > 168)
370 die(EXIT_FAILURE, "DES keys must be 56, 112 or 168 bits long");
374 rand_get(RAND_GLOBAL, p, sz); /* Too much work done here! */
375 for (i = 0; i < sz; i++) {
376 octet x = p[i] | 0x01;
380 p[i] = (p[i] & 0xfe) | (x & 0x01);
382 key_binary(&k->k->k, p, sz);
383 k->k->k.e |= KCAT_SYMM | KF_BURN;
386 dolock(k, &k->k->k, 0);
389 static void alg_rsa(keyopts *k)
394 /* --- Sanity checking --- */
397 die(EXIT_FAILURE, "no shared parameters for RSA keys");
401 /* --- Generate the RSA parameters --- */
403 if (rsa_gen(&rp, k->bits, &rand_global, 0,
404 (k->f & f_quiet) ? 0 : pgen_ev, 0))
405 die(EXIT_FAILURE, "RSA key generation failed");
407 /* --- Run a test encryption --- */
410 grand *g = fibrand_create(rand_global.ops->word(&rand_global));
412 mp *m = mprand_range(MP_NEW, rp.n, g, 0);
417 c = rsa_qpubop(&rpp, MP_NEW, m);
418 c = rsa_qprivop(&rp, c, c, g);
420 if (MP_CMP(c, !=, m))
421 die(EXIT_FAILURE, "test encryption failed");
427 /* --- Allrighty then --- */
431 mpkey(kd, "n", rp.n, KCAT_PUB);
432 mpkey(kd, "e", rp.e, KCAT_PUB);
434 kd = key_structcreate(kd, "private");
436 mpkey(kd, "d", rp.d, KCAT_PRIV | KF_BURN);
437 mpkey(kd, "p", rp.p, KCAT_PRIV | KF_BURN);
438 mpkey(kd, "q", rp.q, KCAT_PRIV | KF_BURN);
439 mpkey(kd, "q-inv", rp.q_inv, KCAT_PRIV | KF_BURN);
440 mpkey(kd, "d-mod-p", rp.dp, KCAT_PRIV | KF_BURN);
441 mpkey(kd, "d-mod-q", rp.dq, KCAT_PRIV | KF_BURN);
442 dolock(k, kd, "private");
447 static void alg_dsaparam(keyopts *k)
449 static const char *pl[] = { "q", "p", "g", 0 };
450 if (!copyparam(k, pl)) {
456 key_data *kd = &k->k->k;
458 /* --- Choose appropriate bit lengths if necessary --- */
465 /* --- Allocate a seed block --- */
467 sz = (k->qbits + 7) >> 3;
469 rand_get(RAND_GLOBAL, p, sz);
471 /* --- Allocate the parameters --- */
473 if (dsa_seed(&dp, k->qbits, k->bits, 0, p, sz,
474 (k->f & f_quiet) ? 0 : pgen_ev, 0))
475 die(EXIT_FAILURE, "DSA parameter generation failed");
477 /* --- Store the parameters --- */
480 mpkey(kd, "q", dp.q, KCAT_SHARE);
481 mpkey(kd, "p", dp.p, KCAT_SHARE);
482 mpkey(kd, "g", dp.g, KCAT_SHARE);
487 /* --- Store the seed for future verification --- */
492 base64_encode(&c, p, sz, &d);
493 base64_encode(&c, 0, 0, &d);
494 key_putattr(k->kf, k->k, "seed", d.buf);
500 static void alg_dsa(keyopts *k)
505 key_data *kd = &k->k->k;
507 /* --- Get the shared parameters --- */
514 /* --- Choose a private key --- */
516 x = mprand_range(MP_NEWSEC, q, &rand_global, 0);
517 mpmont_create(&mm, p);
518 y = mpmont_exp(&mm, MP_NEW, g, x);
520 /* --- Store everything away --- */
522 mpkey(kd, "y", y, KCAT_PUB);
524 kd = key_structcreate(kd, "private");
526 mpkey(kd, "x", x, KCAT_PRIV | KF_BURN);
527 dolock(k, kd, "private");
529 mp_drop(x); mp_drop(y);
532 static void alg_dhparam(keyopts *k)
534 static const char *pl[] = { "p", "q", "g", 0 };
535 if (!copyparam(k, pl)) {
537 key_data *kd = &k->k->k;
542 /* --- Choose a large safe prime number --- */
544 if (dh_gen(&dp, k->qbits, k->bits, 0, &rand_global,
545 (k->f & f_quiet) ? 0 : pgen_ev, 0))
546 die(EXIT_FAILURE, "Diffie-Hellman parameter generation failed");
549 mpkey(kd, "p", dp.p, KCAT_SHARE);
550 mpkey(kd, "q", dp.q, KCAT_SHARE);
551 mpkey(kd, "g", dp.g, KCAT_SHARE);
558 static void alg_dh(keyopts *k)
563 key_data *kd = &k->k->k;
565 /* --- Get the shared parameters --- */
572 /* --- Choose a suitable private key --- *
574 * Since %$g$% has order %$q$%, choose %$x < q$%.
577 x = mprand_range(MP_NEWSEC, q, &rand_global, 0);
579 /* --- Compute the public key %$y = g^x \bmod p$% --- */
581 mpmont_create(&mm, p);
582 y = mpmont_exp(&mm, MP_NEW, g, x);
585 /* --- Store everything away --- */
587 mpkey(kd, "y", y, KCAT_PUB);
589 kd = key_structcreate(kd, "private");
591 mpkey(kd, "x", x, KCAT_PRIV | KF_BURN);
592 dolock(k, kd, "private");
594 mp_drop(x); mp_drop(y);
597 static void alg_bbs(keyopts *k)
602 /* --- Sanity checking --- */
605 die(EXIT_FAILURE, "no shared parameters for Blum-Blum-Shub keys");
609 /* --- Generate the BBS parameters --- */
611 if (bbs_gen(&bp, k->bits, &rand_global, 0,
612 (k->f & f_quiet) ? 0 : pgen_ev, 0))
613 die(EXIT_FAILURE, "Blum-Blum-Shub key generation failed");
615 /* --- Allrighty then --- */
619 mpkey(kd, "n", bp.n, KCAT_PUB);
621 kd = key_structcreate(kd, "private");
623 mpkey(kd, "p", bp.p, KCAT_PRIV | KF_BURN);
624 mpkey(kd, "q", bp.q, KCAT_PRIV | KF_BURN);
625 dolock(k, kd, "private");
630 /* --- The algorithm tables --- */
632 typedef struct keyalg {
634 void (*proc)(keyopts *o);
638 static keyalg algtab[] = {
639 { "binary", alg_binary, "Plain binary data" },
640 { "des", alg_des, "Binary with DES-style parity" },
641 { "rsa", alg_rsa, "RSA public-key encryption" },
642 { "dsa", alg_dsa, "DSA digital signatures" },
643 { "dsa-param", alg_dsaparam, "DSA shared parameters" },
644 { "dh", alg_dh, "Diffie-Hellman key exchange" },
645 { "dh-param", alg_dhparam, "Diffie-Hellman parameters" },
646 { "bbs", alg_bbs, "Blum-Blum-Shub generator" },
650 /* --- @cmd_add@ --- */
652 static int cmd_add(int argc, char *argv[])
655 time_t exp = KEXP_EXPIRE;
656 const char *tag = 0, *ptag = 0;
658 keyalg *alg = algtab;
659 const char *rtag = 0;
660 keyopts k = { 0, 0, DSTR_INIT, 0, 0, 0, 0 };
662 /* --- Parse options for the subcommand --- */
665 static struct option opt[] = {
666 { "algorithm", OPTF_ARGREQ, 0, 'a' },
667 { "bits", OPTF_ARGREQ, 0, 'b' },
668 { "qbits", OPTF_ARGREQ, 0, 'B' },
669 { "parameters", OPTF_ARGREQ, 0, 'p' },
670 { "expire", OPTF_ARGREQ, 0, 'e' },
671 { "comment", OPTF_ARGREQ, 0, 'c' },
672 { "tag", OPTF_ARGREQ, 0, 't' },
673 { "rand-id", OPTF_ARGREQ, 0, 'r' },
674 { "lock", 0, 0, 'l' },
675 { "quiet", 0, 0, 'q' },
678 int i = mdwopt(argc, argv, "+a:b:B:p:e:c:t:r:lq", opt, 0, 0, 0);
682 /* --- Handle the various options --- */
686 /* --- Read an algorithm name --- */
690 size_t sz = strlen(optarg);
692 if (strcmp(optarg, "list") == 0) {
693 for (a = algtab; a->name; a++)
694 printf("%-10s %s\n", a->name, a->help);
699 for (a = algtab; a->name; a++) {
700 if (strncmp(optarg, a->name, sz) == 0) {
701 if (a->name[sz] == 0) {
705 die(EXIT_FAILURE, "ambiguous algorithm name `%s'", optarg);
711 die(EXIT_FAILURE, "unknown algorithm name `%s'", optarg);
714 /* --- Bits must be nonzero and a multiple of 8 --- */
718 k.bits = strtoul(optarg, &p, 0);
719 if (k.bits == 0 || *p != 0)
720 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
725 k.qbits = strtoul(optarg, &p, 0);
726 if (k.qbits == 0 || *p != 0)
727 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
730 /* --- Parameter selection --- */
736 /* --- Expiry dates get passed to @get_date@ for parsing --- */
739 if (strncmp(optarg, "forever", strlen(optarg)) == 0)
742 exp = get_date(optarg, 0);
744 die(EXIT_FAILURE, "bad expiry date `%s'", optarg);
748 /* --- Store comments without interpretation --- */
751 if (key_chkcomment(optarg))
752 die(EXIT_FAILURE, "bad comment string `%s'", optarg);
756 /* --- Store tags --- */
759 if (key_chkident(optarg))
760 die(EXIT_FAILURE, "bad tag string `%s'", optarg);
764 /* --- Other flags --- */
776 /* --- Other things are bogus --- */
784 /* --- Various sorts of bogosity --- */
786 if ((k.f & f_bogus) || optind + 1 > argc) {
788 "Usage: add [options] type [attr...]");
790 if (key_chkident(argv[optind]))
791 die(EXIT_FAILURE, "bad key type `%s'", argv[optind]);
793 /* --- Set up various bits of the state --- */
795 if (exp == KEXP_EXPIRE)
796 exp = time(0) + 14 * 24 * 60 * 60;
798 /* --- Open the file and create the basic key block --- *
800 * Keep on generating keyids until one of them doesn't collide.
803 doopen(&f, KOPEN_WRITE);
806 /* --- Key the generator --- */
811 uint32 id = rand_global.ops->word(&rand_global);
813 k.k = key_new(&f, id, argv[optind], exp, &err);
816 if (err != KERR_DUPID)
817 die(EXIT_FAILURE, "error adding new key: %s", key_strerror(err));
820 /* --- Set various simple attributes --- */
823 int err = key_settag(&f, k.k, tag);
825 die(EXIT_FAILURE, "error setting key tag: %s", key_strerror(err));
829 int err = key_setcomment(&f, k.k, c);
831 die(EXIT_FAILURE, "error setting key comment: %s", key_strerror(err));
834 setattr(&f, k.k, argv + optind + 1);
836 key_fulltag(k.k, &k.tag);
838 /* --- Find the parameter key --- */
841 if ((k.p = key_bytag(&f, ptag)) == 0)
842 die(EXIT_FAILURE, "parameter key `%s' not found", ptag);
843 if ((k.p->k.e & KF_ENCMASK) != KENC_STRUCT)
844 die(EXIT_FAILURE, "parameter key `%s' is not structured", ptag);
847 /* --- Now generate the actual key data --- */
857 /*----- Key listing -------------------------------------------------------*/
859 /* --- Listing options --- */
861 typedef struct listopts {
862 const char *tfmt; /* Date format (@strftime@-style) */
863 int v; /* Verbosity level */
864 unsigned f; /* Various flags */
865 time_t t; /* Time now (for key expiry) */
866 key_filter kf; /* Filter for matching keys */
869 /* --- Listing flags --- */
872 f_newline = 2, /* Write newline before next entry */
873 f_attr = 4, /* Written at least one attribute */
874 f_utc = 8 /* Emit UTC time, not local time */
877 /* --- @showkeydata@ --- *
879 * Arguments: @key_data *k@ = pointer to key to write
880 * @int ind@ = indentation level
881 * @listopts *o@ = listing options
882 * @dstr *d@ = tag string for this subkey
886 * Use: Emits a piece of key data in a human-readable format.
889 static void showkeydata(key_data *k, int ind, listopts *o, dstr *d)
891 #define INDENT(i) do { \
893 for (_i = 0; _i < (i); _i++) { \
898 switch (k->e & KF_ENCMASK) {
900 /* --- Binary key data --- *
902 * Emit as a simple hex dump.
906 const octet *p = k->u.k.k;
907 const octet *l = p + k->u.k.sz;
915 } else if (sz % 8 == 0)
919 printf("%02x", *p++);
924 fputs("}\n", stdout);
927 /* --- Encrypted data --- *
929 * If the user is sufficiently keen, ask for a passphrase and decrypt the
930 * key. Otherwise just say that it's encrypted and move on.
935 fputs(" encrypted\n", stdout);
938 if (key_punlock(d->buf, k, &kd))
939 printf(" <failed to unlock %s>\n", d->buf);
941 fputs(" encrypted", stdout);
942 showkeydata(&kd, ind, o, d);
948 /* --- Integer keys --- *
950 * Emit as a large integer in decimal. This makes using the key in
951 * `calc' or whatever easier.
956 mp_writefile(k->u.m, stdout, 10);
960 /* --- Structured keys --- *
962 * Just iterate over the subkeys.
970 fputs(" {\n", stdout);
971 for (sym_mkiter(&i, &k->u.s); (ks = sym_next(&i)) != 0; ) {
972 if (!key_match(&ks->k, &o->kf))
975 printf("%s =", SYM_NAME(ks));
977 dstr_putf(d, ".%s", SYM_NAME(ks));
978 showkeydata(&ks->k, ind + 2, o, d);
981 fputs("}\n", stdout);
988 /* --- @showkey@ --- *
990 * Arguments: @key *k@ = pointer to key to show
991 * @listopts *o@ = pointer to listing options
995 * Use: Emits a listing of a particular key.
998 static void showkey(key *k, listopts *o)
1000 char ebuf[24], dbuf[24];
1003 /* --- Skip the key if the filter doesn't match --- */
1005 if (!key_match(&k->k, &o->kf))
1008 /* --- Sort out the expiry and deletion times --- */
1010 if (KEY_EXPIRED(o->t, k->exp))
1011 strcpy(ebuf, "expired");
1012 else if (k->exp == KEXP_FOREVER)
1013 strcpy(ebuf, "forever");
1015 tm = (o->f & f_utc) ? gmtime(&k->exp) : localtime(&k->exp);
1016 strftime(ebuf, sizeof(ebuf), o->tfmt, tm);
1019 if (KEY_EXPIRED(o->t, k->del))
1020 strcpy(dbuf, "deleted");
1021 else if (k->del == KEXP_FOREVER)
1022 strcpy(dbuf, "forever");
1024 tm = (o->f & f_utc) ? gmtime(&k->del) : localtime(&k->del);
1025 strftime(dbuf, sizeof(dbuf), o->tfmt, tm);
1028 /* --- If in compact format, just display and quit --- */
1031 if (!(o->f & f_newline)) {
1032 printf("%8s %-20s %-20s %-10s %-10s\n",
1033 "Id", "Tag", "Type", "Expire", "Delete");
1035 printf("%08lx %-20s %-20s %-10s %-10s\n",
1036 (unsigned long)k->id, k->tag ? k->tag : "<none>",
1037 k->type, ebuf, dbuf);
1042 /* --- Display the standard header --- */
1044 if (o->f & f_newline)
1045 fputc('\n', stdout);
1046 printf("keyid: %08lx\n", (unsigned long)k->id);
1047 printf("tag: %s\n", k->tag ? k->tag : "<none>");
1048 printf("type: %s\n", k->type);
1049 printf("expiry: %s\n", ebuf);
1050 printf("delete: %s\n", dbuf);
1051 printf("comment: %s\n", k->c ? k->c : "<none>");
1053 /* --- Display the attributes --- */
1057 const char *av, *an;
1060 printf("attributes:");
1061 for (key_mkattriter(&i, k); key_nextattr(&i, &an, &av); ) {
1062 printf("\n\t%s = %s", an, av);
1066 fputc('\n', stdout);
1071 /* --- If dumping requested, dump the raw key data --- */
1075 fputs("key:", stdout);
1077 showkeydata(&k->k, 0, o, &d);
1084 /* --- @cmd_list@ --- */
1086 static int cmd_list(int argc, char *argv[])
1090 listopts o = { 0, 0, 0, 0, { 0, 0 } };
1092 /* --- Parse subcommand options --- */
1095 static struct option opt[] = {
1096 { "quiet", 0, 0, 'q' },
1097 { "verbose", 0, 0, 'v' },
1098 { "utc", 0, 0, 'u' },
1099 { "filter", OPTF_ARGREQ, 0, 'f' },
1102 int i = mdwopt(argc, argv, "+uqvf:", opt, 0, 0, 0);
1119 int e = key_readflags(optarg, &p, &o.kf.f, &o.kf.m);
1121 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1130 die(EXIT_FAILURE, "Usage: list [-uqv] [-f filter] [tag...]");
1132 /* --- Open the key file --- */
1134 doopen(&f, KOPEN_READ);
1137 /* --- Set up the time format --- */
1140 o.tfmt = "%Y-%m-%d";
1141 else if (o.f & f_utc)
1142 o.tfmt = "%Y-%m-%d %H:%M:%S UTC";
1144 o.tfmt = "%Y-%m-%d %H:%M:%S %Z";
1146 /* --- If specific keys were requested use them, otherwise do all --- *
1148 * Some day, this might turn into a wildcard match.
1151 if (optind < argc) {
1153 if ((k = key_bytag(&f, argv[optind])) != 0)
1156 moan("key `%s' not found", argv[optind]);
1160 } while (optind < argc);
1163 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1171 return (EXIT_FAILURE);
1176 /*----- Command implementation --------------------------------------------*/
1178 /* --- @cmd_expire@ --- */
1180 static int cmd_expire(int argc, char *argv[])
1188 die(EXIT_FAILURE, "Usage: expire tag...");
1189 doopen(&f, KOPEN_WRITE);
1190 for (i = 1; i < argc; i++) {
1191 if ((k = key_bytag(&f, argv[i])) != 0)
1194 moan("key `%s' not found", argv[i]);
1202 /* --- @cmd_delete@ --- */
1204 static int cmd_delete(int argc, char *argv[])
1212 die(EXIT_FAILURE, "Usage: delete tag...");
1213 doopen(&f, KOPEN_WRITE);
1214 for (i = 1; i < argc; i++) {
1215 if ((k = key_bytag(&f, argv[i])) != 0)
1218 moan("key `%s' not found", argv[i]);
1226 /* --- @cmd_setattr@ --- */
1228 static int cmd_setattr(int argc, char *argv[])
1234 die(EXIT_FAILURE, "Usage: setattr tag attr...");
1235 doopen(&f, KOPEN_WRITE);
1236 if ((k = key_bytag(&f, argv[1])) == 0)
1237 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1238 setattr(&f, k, argv + 2);
1243 /* --- @cmd_finger@ --- */
1245 static void fingerprint(key *k, const key_filter *kf)
1248 octet hash[RMD160_HASHSZ];
1252 if (!key_encode(&k->k, &d, kf))
1255 rmd160_hash(&r, d.buf, d.len);
1256 rmd160_done(&r, hash);
1260 for (i = 0; i < sizeof(hash); i++) {
1261 if (i && i % 4 == 0)
1263 printf("%02x", hash[i]);
1265 printf(" %s\n", d.buf);
1269 static int cmd_finger(int argc, char *argv[])
1273 key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1276 static struct option opt[] = {
1277 { "filter", OPTF_ARGREQ, 0, 'f' },
1280 int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
1286 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1288 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1296 argv += optind; argc -= optind;
1298 die(EXIT_FAILURE, "Usage: fingerprint [-f filter] [tag...]");
1300 doopen(&f, KOPEN_READ);
1304 for (i = 0; i < argc; i++) {
1305 key *k = key_bytag(&f, argv[i]);
1307 fingerprint(k, &kf);
1310 moan("key `%s' not found", argv[i]);
1316 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1317 fingerprint(k, &kf);
1322 /* --- @cmd_comment@ --- */
1324 static int cmd_comment(int argc, char *argv[])
1330 if (argc < 2 || argc > 3)
1331 die(EXIT_FAILURE, "Usage: comment tag [comment]");
1332 doopen(&f, KOPEN_WRITE);
1333 if ((k = key_bytag(&f, argv[1])) == 0)
1334 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1335 if ((err = key_setcomment(&f, k, argv[2])) != 0)
1336 die(EXIT_FAILURE, "bad comment `%s': %s", argv[2], key_strerror(err));
1341 /* --- @cmd_tag@ --- */
1343 static int cmd_tag(int argc, char *argv[])
1349 if (argc < 2 || argc > 3)
1350 die(EXIT_FAILURE, "Usage: tag tag [new-tag]");
1351 doopen(&f, KOPEN_WRITE);
1352 if ((k = key_bytag(&f, argv[1])) == 0)
1353 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1354 if ((err = key_settag(&f, k, argv[2])) != 0)
1355 die(EXIT_FAILURE, "bad tag `%s': %s", argv[2], key_strerror(err));
1360 /* --- @cmd_lock@ --- */
1362 static int cmd_lock(int argc, char *argv[])
1370 die(EXIT_FAILURE, "Usage: lock qtag");
1371 doopen(&f, KOPEN_WRITE);
1372 if (key_qtag(&f, argv[1], &d, &k, &kd))
1373 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1374 if (kd->e == KENC_ENCRYPT && key_punlock(d.buf, kd, kd))
1375 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
1376 if (key_plock(d.buf, kd, kd))
1377 die(EXIT_FAILURE, "failed to lock key `%s'", d.buf);
1383 /* --- @cmd_unlock@ --- */
1385 static int cmd_unlock(int argc, char *argv[])
1393 die(EXIT_FAILURE, "Usage: unlock qtag");
1394 doopen(&f, KOPEN_WRITE);
1395 if (key_qtag(&f, argv[1], &d, &k, &kd))
1396 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1397 if (kd->e != KENC_ENCRYPT)
1398 die(EXIT_FAILURE, "key `%s' is not encrypted", d.buf);
1399 if (kd->e == KENC_ENCRYPT && key_punlock(d.buf, kd, kd))
1400 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
1406 /* --- @cmd_extract@ --- */
1408 static int cmd_extract(int argc, char *argv[])
1414 key_filter kf = { 0, 0 };
1418 static struct option opt[] = {
1419 { "filter", OPTF_ARGREQ, 0, 'f' },
1422 int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
1428 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1430 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1438 argv += optind; argc -= optind;
1440 die(EXIT_FAILURE, "Usage: extract [-f filter] file [tag...]");
1441 if (strcmp(*argv, "-") == 0)
1443 else if (!(fp = fopen(*argv, "w"))) {
1444 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
1445 *argv, strerror(errno));
1448 doopen(&f, KOPEN_READ);
1452 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1453 key_extract(&f, k, fp, &kf);
1455 for (i = 1; i < argc; i++) {
1456 if ((k = key_bytag(&f, argv[i])) != 0)
1457 key_extract(&f, k, fp, &kf);
1459 moan("key `%s' not found", argv[i]);
1465 die(EXIT_FAILURE, "error writing file: %s", strerror(errno));
1470 /* --- @cmd_tidy@ --- */
1472 static int cmd_tidy(int argc, char *argv[])
1476 die(EXIT_FAILURE, "usage: tidy");
1477 doopen(&f, KOPEN_WRITE);
1478 f.f |= KF_MODIFIED; /* Nasty hack */
1483 /* --- @cmd_merge@ --- */
1485 static int cmd_merge(int argc, char *argv[])
1491 die(EXIT_FAILURE, "Usage: merge file");
1492 if (strcmp(argv[1], "-") == 0)
1494 else if (!(fp = fopen(argv[1], "r"))) {
1495 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
1496 argv[1], strerror(errno));
1499 doopen(&f, KOPEN_WRITE);
1500 key_merge(&f, argv[1], fp, key_moan, 0);
1505 /*----- Main command table ------------------------------------------------*/
1509 int (*cmd)(int /*argc*/, char */*argv*/[]);
1513 "add [options] type [attr...]\n\
1514 Options: [-lq] [-a alg] [-b|-B bits] [-p param] [-r tag]\n\
1515 [-e expire] [-t tag] [-c comment]"
1517 { "expire", cmd_expire, "expire tag..." },
1518 { "delete", cmd_delete, "delete tag..." },
1519 { "tag", cmd_tag, "tag tag [new-tag]" },
1520 { "setattr", cmd_setattr, "setattr tag attr..." },
1521 { "comment", cmd_comment, "comment tag [comment]" },
1522 { "lock", cmd_lock, "lock qtag" },
1523 { "unlock", cmd_unlock, "unlock qtag" },
1524 { "list", cmd_list, "list [-uqv] [-f filter] [tag...]" },
1525 { "fingerprint", cmd_finger, "fingerprint [-f filter] [tag...]" },
1526 { "tidy", cmd_tidy, "tidy" },
1527 { "extract", cmd_extract, "extract [-f filter] file [tag...]" },
1528 { "merge", cmd_merge, "merge file" },
1532 typedef struct cmd cmd;
1534 /*----- Main code ---------------------------------------------------------*/
1536 /* --- Helpful GNUy functions --- */
1538 void usage(FILE *fp)
1540 pquis(fp, "Usage: $ [-k file] [-i tag] [-t type] command [args]\n");
1543 void version(FILE *fp)
1545 pquis(fp, "$, Catacomb version " VERSION "\n");
1555 Performs various simple key management operations. Command line options\n\
1558 -h, --help Display this help text.\n\
1559 -v, --version Display version number.\n\
1560 -u, --usage Display short usage summary.\n\
1562 -k, --keyring=FILE Read and write keys in FILE.\n\
1563 -i, --id=TAG Use key TAG for random number generator.\n\
1564 -t, --type=TYPE Use key TYPE for random number generator.\n\
1566 The following commands are understood:\n\n",
1568 for (c = cmds; c->name; c++)
1569 fprintf(fp, "%s\n", c->help);
1574 * Arguments: @int argc@ = number of command line arguments
1575 * @char *argv[]@ = array of command line arguments
1577 * Returns: Nonzero on failure.
1579 * Use: Main program. Performs simple key management functions.
1582 int main(int argc, char *argv[])
1590 /* --- Initialization --- */
1595 /* --- Parse command line options --- */
1598 static struct option opt[] = {
1600 /* --- Standard GNUy help options --- */
1602 { "help", 0, 0, 'h' },
1603 { "version", 0, 0, 'v' },
1604 { "usage", 0, 0, 'u' },
1606 /* --- Real live useful options --- */
1608 { "keyring", OPTF_ARGREQ, 0, 'k' },
1609 { "id", OPTF_ARGREQ, 0, 'i' },
1610 { "type", OPTF_ARGREQ, 0, 't' },
1612 /* --- Magic terminator --- */
1616 int i = mdwopt(argc, argv, "+hvu k:i:t:", opt, 0, 0, 0);
1622 /* --- GNU help options --- */
1633 /* --- Real useful options --- */
1639 /* --- Bogosity --- */
1647 /* --- Complain about excessive bogons --- */
1649 if (f & f_bogus || optind == argc) {
1654 /* --- Initialize the Catacomb random number generator --- */
1656 rand_noisesrc(RAND_GLOBAL, &noise_source);
1657 rand_seed(RAND_GLOBAL, 160);
1659 /* --- Dispatch to appropriate command handler --- */
1666 cmd *c, *chosen = 0;
1667 size_t sz = strlen(argv[0]);
1669 for (c = cmds; c->name; c++) {
1670 if (strncmp(argv[0], c->name, sz) == 0) {
1671 if (c->name[sz] == 0) {
1675 die(EXIT_FAILURE, "ambiguous command name `%s'", argv[0]);
1681 die(EXIT_FAILURE, "unknown command name `%s'", argv[0]);
1682 return (chosen->cmd(argc, argv));
1686 /*----- That's all, folks -------------------------------------------------*/