Minor formatting change in listing attributes.
[u/mdw/catacomb] / keyutil.c
1 /* -*-c-*-
2 *
3 * $Id: keyutil.c,v 1.9 2000/08/15 21:40:49 mdw Exp $
4 *
5 * Simple key manager program
6 *
7 * (c) 1999 Straylight/Edgeware
8 */
9
10 /*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Catacomb.
13 *
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.
18 *
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.
23 *
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,
27 * MA 02111-1307, USA.
28 */
29
30 /*----- Revision history --------------------------------------------------*
31 *
32 * $Log: keyutil.c,v $
33 * Revision 1.9 2000/08/15 21:40:49 mdw
34 * Minor formatting change in listing attributes.
35 *
36 * Revision 1.8 2000/07/29 09:59:13 mdw
37 * Support Lim-Lee primes in Diffie-Hellman parameter generation.
38 *
39 * Revision 1.7 2000/07/01 11:18:51 mdw
40 * Use new interfaces for key manipulation.
41 *
42 * Revision 1.6 2000/06/17 11:28:22 mdw
43 * Use secure memory interface from MP library. `rand_getgood' is
44 * deprecated.
45 *
46 * Revision 1.5 2000/02/12 18:21:03 mdw
47 * Overhaul of key management (again).
48 *
49 * Revision 1.4 1999/12/22 15:48:10 mdw
50 * Track new key-management changes. Support new key generation
51 * algorithms.
52 *
53 * Revision 1.3 1999/11/02 15:23:24 mdw
54 * Fix newlines in keyring list.
55 *
56 * Revision 1.2 1999/10/15 21:05:28 mdw
57 * In `key list', show timezone for local times, and support `-u' option
58 * for UTC output.
59 *
60 * Revision 1.1 1999/09/03 08:41:12 mdw
61 * Initial import.
62 *
63 */
64
65 /*----- Header files ------------------------------------------------------*/
66
67 #include "config.h"
68
69 #include <errno.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <time.h>
74
75 #include <mLib/base64.h>
76 #include <mLib/mdwopt.h>
77 #include <mLib/quis.h>
78 #include <mLib/report.h>
79 #include <mLib/sub.h>
80
81 #include <noise.h>
82 #include <rand.h>
83
84 #include "bbs.h"
85 #include "dh.h"
86 #include "dsa.h"
87 #include "fibrand.h"
88 #include "getdate.h"
89 #include "key.h"
90 #include "mp.h"
91 #include "mpmont.h"
92 #include "mprand.h"
93 #include "mptext.h"
94 #include "pgen.h"
95 #include "rsa.h"
96
97 /*----- Handy global state ------------------------------------------------*/
98
99 static const char *keyfile = "keyring";
100
101 /*----- Useful shared functions -------------------------------------------*/
102
103 /* --- @doopen@ --- *
104 *
105 * Arguments: @key_file *f@ = pointer to key file block
106 * @unsigned how@ = method to open file with
107 *
108 * Returns: ---
109 *
110 * Use: Opens a key file and handles errors by panicking
111 * appropriately.
112 */
113
114 static void doopen(key_file *f, unsigned how)
115 {
116 if (key_open(f, keyfile, how, key_moan, 0))
117 die(1, "couldn't open keyring `%s': %s", keyfile, strerror(errno));
118 }
119
120 /* --- @doclose@ --- *
121 *
122 * Arguments: @key_file *f@ = pointer to key file block
123 *
124 * Returns: ---
125 *
126 * Use: Closes a key file and handles errors by panicking
127 * appropriately.
128 */
129
130 static void doclose(key_file *f)
131 {
132 switch (key_close(f)) {
133 case KWRITE_FAIL:
134 die(EXIT_FAILURE, "couldn't write file `%s': %s",
135 keyfile, strerror(errno));
136 case KWRITE_BROKEN:
137 die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
138 keyfile, strerror(errno));
139 }
140 }
141
142 /* --- @setattr@ --- *
143 *
144 * Arguments: @key_file *f@ = pointer to key file block
145 * @key *k@ = pointer to key block
146 * @char *v[]@ = array of assignments (overwritten!)
147 *
148 * Returns: ---
149 *
150 * Use: Applies the attribute assignments to the key.
151 */
152
153 static void setattr(key_file *f, key *k, char *v[])
154 {
155 while (*v) {
156 int err;
157 char *p = *v;
158 size_t eq = strcspn(p, "=");
159 if (p[eq] == 0)
160 moan("invalid assignment: `%s'", p);
161 p[eq] = 0;
162 p += eq + 1;
163 if ((err = key_putattr(f, k, *v, *p ? p : 0)) != 0)
164 die(EXIT_FAILURE, "couldn't set attributes: %s", key_strerror(err));
165 v++;
166 }
167 }
168
169 /*----- Key generation ----------------------------------------------------*/
170
171 /* --- Key generation parameters --- */
172
173 typedef struct keyopts {
174 key_file *kf; /* Pointer to key file */
175 key *k; /* Pointer to the actual key */
176 dstr tag; /* Full tag name for the key */
177 unsigned f; /* Flags for the new key */
178 unsigned bits, qbits; /* Bit length for the new key */
179 key *p; /* Parameters key-data */
180 } keyopts;
181
182 enum {
183 f_bogus = 1, /* Error in parsing */
184 f_lock = 2, /* Passphrase-lock private key */
185 f_quiet = 4, /* Don't show a progress indicator */
186 f_limlee = 8, /* Generate Lim-Lee primes */
187 f_subgroup = 16 /* Generate a subgroup */
188 };
189
190 /* --- @dolock@ --- *
191 *
192 * Arguments: @keyopts *k@ = key generation options
193 * @key_data *kd@ = pointer to key data to lock
194 * @const char *t@ = tag suffix or null
195 *
196 * Returns: ---
197 *
198 * Use: Does passphrase locking on new keys.
199 */
200
201 static void dolock(keyopts *k, key_data *kd, const char *t)
202 {
203 if (!(k->f & f_lock))
204 return;
205 if (t)
206 dstr_putf(&k->tag, ".%s", t);
207 if (key_plock(k->tag.buf, kd, kd))
208 die(EXIT_FAILURE, "couldn't lock key");
209 }
210
211 /* --- @mpkey@ --- *
212 *
213 * Arguments: @key_data *kd@ = pointer to parent key block
214 * @const char *tag@ = pointer to tag string
215 * @mp *m@ = integer to store
216 * @unsigned f@ = flags to set
217 *
218 * Returns: ---
219 *
220 * Use: Sets a multiprecision integer subkey.
221 */
222
223 static void mpkey(key_data *kd, const char *tag, mp *m, unsigned f)
224 {
225 key_data *kkd = key_structcreate(kd, tag);
226 key_mp(kkd, m);
227 kkd->e |= f;
228 }
229
230 /* --- @copyparam@ --- *
231 *
232 * Arguments: @keyopts *k@ = pointer to key options
233 * @const char **pp@ = checklist of parameters
234 *
235 * Returns: Nonzero if parameters copied; zero if you have to generate
236 * them.
237 *
238 * Use: Copies parameters from a source key to the current one.
239 */
240
241 static int copyparam(keyopts *k, const char **pp)
242 {
243 key_filter kf;
244
245 /* --- Quick check if no parameters supplied --- */
246
247 if (!k->p)
248 return (0);
249
250 /* --- Run through the checklist --- */
251
252 while (*pp) {
253 key_data *kd = key_structfind(&k->p->k, *pp);
254 if (!kd)
255 die(EXIT_FAILURE, "bad parameter key: parameter `%s' not found", *pp);
256 if ((kd->e & KF_CATMASK) != KCAT_SHARE)
257 die(EXIT_FAILURE, "bad parameter key: subkey `%s' is not shared", *pp);
258 pp++;
259 }
260
261 /* --- Copy over the parameters --- */
262
263 kf.f = KCAT_SHARE;
264 kf.m = KF_CATMASK;
265 if (!key_copy(&k->k->k, &k->p->k, &kf))
266 die(EXIT_FAILURE, "unexpected failure while copying parameters");
267 return (1);
268 }
269
270 /* --- @getmp@ --- *
271 *
272 * Arguments: @key_data *k@ = pointer to key data block
273 * @const char *tag@ = tag string to use
274 *
275 * Returns: Pointer to multiprecision integer key item.
276 *
277 * Use: Fetches an MP key component.
278 */
279
280 static mp *getmp(key_data *k, const char *tag)
281 {
282 k = key_structfind(k, tag);
283 if (!k)
284 die(EXIT_FAILURE, "unexpected failure looking up subkey `%s'", tag);
285 if ((k->e & KF_ENCMASK) != KENC_MP)
286 die(EXIT_FAILURE, "subkey `%s' has an incompatible type");
287 return (k->u.m);
288 }
289
290 /* --- @keyrand@ --- *
291 *
292 * Arguments: @key_file *kf@ = pointer to key file
293 * @const char *id@ = pointer to key id (or null)
294 *
295 * Returns: ---
296 *
297 * Use: Keys the random number generator.
298 */
299
300 static void keyrand(key_file *kf, const char *id)
301 {
302 key *k;
303
304 /* --- Find the key --- */
305
306 if (id) {
307 if ((k = key_bytag(kf, id)) == 0)
308 die(EXIT_FAILURE, "key `%s' not found", id);
309 } else
310 k = key_bytype(kf, "catacomb-rand");
311
312 if (k) {
313 key_data *kd = &k->k, kkd;
314
315 again:
316 switch (kd->e & KF_ENCMASK) {
317 case KENC_BINARY:
318 break;
319 case KENC_ENCRYPT: {
320 dstr d = DSTR_INIT;
321 key_fulltag(k, &d);
322 if (key_punlock(d.buf, kd, &kkd))
323 die(EXIT_FAILURE, "error unlocking key `%s'", d.buf);
324 dstr_destroy(&d);
325 kd = &kkd;
326 } goto again;
327 default: {
328 dstr d = DSTR_INIT;
329 key_fulltag(k, &d);
330 die(EXIT_FAILURE, "bad encoding type for key `%s'", d.buf);
331 } break;
332 }
333
334 /* --- Key the generator --- */
335
336 rand_key(RAND_GLOBAL, kd->u.k.k, kd->u.k.sz);
337 if (kd == &kkd)
338 key_destroy(&kkd);
339 }
340 }
341
342 /* --- Key generation algorithms --- */
343
344 static void alg_binary(keyopts *k)
345 {
346 unsigned sz;
347 unsigned m;
348 octet *p;
349
350 if (!k->bits)
351 k->bits = 128;
352 if (k->p)
353 die(EXIT_FAILURE, "no shared parameters for binary keys");
354
355 sz = (k->bits + 7) >> 3;
356 p = sub_alloc(sz);
357 m = (1 << (((k->bits - 1) & 7) + 1)) - 1;
358 rand_get(RAND_GLOBAL, p, sz);
359 *p &= m;
360 key_binary(&k->k->k, p, sz);
361 k->k->k.e |= KCAT_SYMM | KF_BURN;
362 memset(p, 0, sz);
363 sub_free(p, sz);
364 dolock(k, &k->k->k, 0);
365 }
366
367 static void alg_des(keyopts *k)
368 {
369 unsigned sz;
370 octet *p;
371 int i;
372
373 if (!k->bits)
374 k->bits = 112;
375 if (k->p)
376 die(EXIT_FAILURE, "no shared parameters for DES keys");
377 if (k->bits % 56 || k->bits > 168)
378 die(EXIT_FAILURE, "DES keys must be 56, 112 or 168 bits long");
379
380 sz = k->bits / 7;
381 p = sub_alloc(sz);
382 rand_get(RAND_GLOBAL, p, sz); /* Too much work done here! */
383 for (i = 0; i < sz; i++) {
384 octet x = p[i] | 0x01;
385 x = x ^ (x >> 4);
386 x = x ^ (x >> 2);
387 x = x ^ (x >> 1);
388 p[i] = (p[i] & 0xfe) | (x & 0x01);
389 }
390 key_binary(&k->k->k, p, sz);
391 k->k->k.e |= KCAT_SYMM | KF_BURN;
392 memset(p, 0, sz);
393 sub_free(p, sz);
394 dolock(k, &k->k->k, 0);
395 }
396
397 static void alg_rsa(keyopts *k)
398 {
399 rsa_priv rp;
400 key_data *kd;
401
402 /* --- Sanity checking --- */
403
404 if (k->p)
405 die(EXIT_FAILURE, "no shared parameters for RSA keys");
406 if (!k->bits)
407 k->bits = 1024;
408
409 /* --- Generate the RSA parameters --- */
410
411 if (rsa_gen(&rp, k->bits, &rand_global, 0,
412 (k->f & f_quiet) ? 0 : pgen_ev, 0))
413 die(EXIT_FAILURE, "RSA key generation failed");
414
415 /* --- Run a test encryption --- */
416
417 {
418 grand *g = fibrand_create(rand_global.ops->word(&rand_global));
419 rsa_pub rpp;
420 mp *m = mprand_range(MP_NEW, rp.n, g, 0);
421 mp *c;
422
423 rpp.n = rp.n;
424 rpp.e = rp.e;
425 c = rsa_qpubop(&rpp, MP_NEW, m);
426 c = rsa_qprivop(&rp, c, c, g);
427
428 if (MP_CMP(c, !=, m))
429 die(EXIT_FAILURE, "test encryption failed");
430 mp_drop(c);
431 mp_drop(m);
432 g->ops->destroy(g);
433 }
434
435 /* --- Allrighty then --- */
436
437 kd = &k->k->k;
438 key_structure(kd);
439 mpkey(kd, "n", rp.n, KCAT_PUB);
440 mpkey(kd, "e", rp.e, KCAT_PUB);
441
442 kd = key_structcreate(kd, "private");
443 key_structure(kd);
444 mpkey(kd, "d", rp.d, KCAT_PRIV | KF_BURN);
445 mpkey(kd, "p", rp.p, KCAT_PRIV | KF_BURN);
446 mpkey(kd, "q", rp.q, KCAT_PRIV | KF_BURN);
447 mpkey(kd, "q-inv", rp.q_inv, KCAT_PRIV | KF_BURN);
448 mpkey(kd, "d-mod-p", rp.dp, KCAT_PRIV | KF_BURN);
449 mpkey(kd, "d-mod-q", rp.dq, KCAT_PRIV | KF_BURN);
450 dolock(k, kd, "private");
451
452 rsa_privfree(&rp);
453 }
454
455 static void alg_dsaparam(keyopts *k)
456 {
457 static const char *pl[] = { "q", "p", "g", 0 };
458 if (!copyparam(k, pl)) {
459 dsa_param dp;
460 octet *p;
461 size_t sz;
462 dstr d = DSTR_INIT;
463 base64_ctx c;
464 key_data *kd = &k->k->k;
465
466 /* --- Choose appropriate bit lengths if necessary --- */
467
468 if (!k->qbits)
469 k->qbits = 160;
470 if (!k->bits)
471 k->bits = 768;
472
473 /* --- Allocate a seed block --- */
474
475 sz = (k->qbits + 7) >> 3;
476 p = sub_alloc(sz);
477 rand_get(RAND_GLOBAL, p, sz);
478
479 /* --- Allocate the parameters --- */
480
481 if (dsa_gen(&dp, k->qbits, k->bits, 0, p, sz,
482 (k->f & f_quiet) ? 0 : pgen_ev, 0))
483 die(EXIT_FAILURE, "DSA parameter generation failed");
484
485 /* --- Store the parameters --- */
486
487 key_structure(kd);
488 mpkey(kd, "q", dp.q, KCAT_SHARE);
489 mpkey(kd, "p", dp.p, KCAT_SHARE);
490 mpkey(kd, "g", dp.g, KCAT_SHARE);
491 mp_drop(dp.q);
492 mp_drop(dp.p);
493 mp_drop(dp.g);
494
495 /* --- Store the seed for future verification --- */
496
497 base64_init(&c);
498 c.maxline = 0;
499 c.indent = "";
500 base64_encode(&c, p, sz, &d);
501 base64_encode(&c, 0, 0, &d);
502 key_putattr(k->kf, k->k, "seed", d.buf);
503 sub_free(p, sz);
504 dstr_destroy(&d);
505 }
506 }
507
508 static void alg_dsa(keyopts *k)
509 {
510 mp *q, *p, *g;
511 mp *x, *y;
512 mpmont mm;
513 key_data *kd = &k->k->k;
514
515 /* --- Get the shared parameters --- */
516
517 alg_dsaparam(k);
518 q = getmp(kd, "q");
519 p = getmp(kd, "p");
520 g = getmp(kd, "g");
521
522 /* --- Choose a private key --- */
523
524 x = mprand_range(MP_NEWSEC, q, &rand_global, 0);
525 mpmont_create(&mm, p);
526 y = mpmont_exp(&mm, MP_NEW, g, x);
527
528 /* --- Store everything away --- */
529
530 mpkey(kd, "y", y, KCAT_PUB);
531
532 kd = key_structcreate(kd, "private");
533 key_structure(kd);
534 mpkey(kd, "x", x, KCAT_PRIV | KF_BURN);
535 dolock(k, kd, "private");
536
537 mp_drop(x); mp_drop(y);
538 }
539
540 static void alg_dhparam(keyopts *k)
541 {
542 static const char *pl[] = { "p", "q", "g", 0 };
543 if (!copyparam(k, pl)) {
544 dh_param dp;
545 key_data *kd = &k->k->k;
546 int rc;
547
548 if (!k->bits)
549 k->bits = 1024;
550
551 /* --- Choose a large safe prime number --- */
552
553 if (k->f & f_limlee) {
554 mp **f;
555 size_t nf;
556 if (!k->qbits)
557 k->qbits = 256;
558 rc = dh_limlee(&dp, k->qbits, k->bits,
559 (k->f & f_subgroup) ? DH_SUBGROUP : 0,
560 0, &rand_global, (k->f & f_quiet) ? 0 : pgen_ev, 0,
561 (k->f & f_quiet) ? 0 : pgen_evspin, 0, &nf, &f);
562 if (!rc) {
563 dstr d = DSTR_INIT;
564 size_t i;
565 for (i = 0; i < nf; i++) {
566 if (i)
567 dstr_puts(&d, ", ");
568 mp_writedstr(f[i], &d, 10);
569 mp_drop(f[i]);
570 }
571 key_putattr(k->kf, k->k, "factors", d.buf);
572 dstr_destroy(&d);
573 }
574 } else
575 rc = dh_gen(&dp, k->qbits, k->bits, 0, &rand_global,
576 (k->f & f_quiet) ? 0 : pgen_ev, 0);
577
578 if (rc)
579 die(EXIT_FAILURE, "Diffie-Hellman parameter generation failed");
580
581 key_structure(kd);
582 mpkey(kd, "p", dp.p, KCAT_SHARE);
583 mpkey(kd, "q", dp.q, KCAT_SHARE);
584 mpkey(kd, "g", dp.g, KCAT_SHARE);
585 mp_drop(dp.q);
586 mp_drop(dp.p);
587 mp_drop(dp.g);
588 }
589 }
590
591 static void alg_dh(keyopts *k)
592 {
593 mp *x, *y;
594 mp *p, *q, *g;
595 mpmont mm;
596 key_data *kd = &k->k->k;
597
598 /* --- Get the shared parameters --- */
599
600 alg_dhparam(k);
601 p = getmp(kd, "p");
602 q = getmp(kd, "q");
603 g = getmp(kd, "g");
604
605 /* --- Choose a suitable private key --- *
606 *
607 * Since %$g$% has order %$q$%, choose %$x < q$%.
608 */
609
610 x = mprand_range(MP_NEWSEC, q, &rand_global, 0);
611
612 /* --- Compute the public key %$y = g^x \bmod p$% --- */
613
614 mpmont_create(&mm, p);
615 y = mpmont_exp(&mm, MP_NEW, g, x);
616 mpmont_destroy(&mm);
617
618 /* --- Store everything away --- */
619
620 mpkey(kd, "y", y, KCAT_PUB);
621
622 kd = key_structcreate(kd, "private");
623 key_structure(kd);
624 mpkey(kd, "x", x, KCAT_PRIV | KF_BURN);
625 dolock(k, kd, "private");
626
627 mp_drop(x); mp_drop(y);
628 }
629
630 static void alg_bbs(keyopts *k)
631 {
632 bbs_priv bp;
633 key_data *kd;
634
635 /* --- Sanity checking --- */
636
637 if (k->p)
638 die(EXIT_FAILURE, "no shared parameters for Blum-Blum-Shub keys");
639 if (!k->bits)
640 k->bits = 1024;
641
642 /* --- Generate the BBS parameters --- */
643
644 if (bbs_gen(&bp, k->bits, &rand_global, 0,
645 (k->f & f_quiet) ? 0 : pgen_ev, 0))
646 die(EXIT_FAILURE, "Blum-Blum-Shub key generation failed");
647
648 /* --- Allrighty then --- */
649
650 kd = &k->k->k;
651 key_structure(kd);
652 mpkey(kd, "n", bp.n, KCAT_PUB);
653
654 kd = key_structcreate(kd, "private");
655 key_structure(kd);
656 mpkey(kd, "p", bp.p, KCAT_PRIV | KF_BURN);
657 mpkey(kd, "q", bp.q, KCAT_PRIV | KF_BURN);
658 dolock(k, kd, "private");
659
660 bbs_privfree(&bp);
661 }
662
663 /* --- The algorithm tables --- */
664
665 typedef struct keyalg {
666 const char *name;
667 void (*proc)(keyopts *o);
668 const char *help;
669 } keyalg;
670
671 static keyalg algtab[] = {
672 { "binary", alg_binary, "Plain binary data" },
673 { "des", alg_des, "Binary with DES-style parity" },
674 { "rsa", alg_rsa, "RSA public-key encryption" },
675 { "dsa", alg_dsa, "DSA digital signatures" },
676 { "dsa-param", alg_dsaparam, "DSA shared parameters" },
677 { "dh", alg_dh, "Diffie-Hellman key exchange" },
678 { "dh-param", alg_dhparam, "Diffie-Hellman parameters" },
679 { "bbs", alg_bbs, "Blum-Blum-Shub generator" },
680 { 0, 0 }
681 };
682
683 /* --- @cmd_add@ --- */
684
685 static int cmd_add(int argc, char *argv[])
686 {
687 key_file f;
688 time_t exp = KEXP_EXPIRE;
689 const char *tag = 0, *ptag = 0;
690 const char *c = 0;
691 keyalg *alg = algtab;
692 const char *rtag = 0;
693 keyopts k = { 0, 0, DSTR_INIT, 0, 0, 0, 0 };
694
695 /* --- Parse options for the subcommand --- */
696
697 for (;;) {
698 static struct option opt[] = {
699 { "algorithm", OPTF_ARGREQ, 0, 'a' },
700 { "bits", OPTF_ARGREQ, 0, 'b' },
701 { "qbits", OPTF_ARGREQ, 0, 'B' },
702 { "parameters", OPTF_ARGREQ, 0, 'p' },
703 { "expire", OPTF_ARGREQ, 0, 'e' },
704 { "comment", OPTF_ARGREQ, 0, 'c' },
705 { "tag", OPTF_ARGREQ, 0, 't' },
706 { "rand-id", OPTF_ARGREQ, 0, 'r' },
707 { "lock", 0, 0, 'l' },
708 { "quiet", 0, 0, 'q' },
709 { "lim-lee", 0, 0, 'L' },
710 { "subgroup", 0, 0, 'S' },
711 { 0, 0, 0, 0 }
712 };
713 int i = mdwopt(argc, argv, "+a:b:B:p:e:c:t:r:lqLS", opt, 0, 0, 0);
714 if (i < 0)
715 break;
716
717 /* --- Handle the various options --- */
718
719 switch (i) {
720
721 /* --- Read an algorithm name --- */
722
723 case 'a': {
724 keyalg *a;
725 size_t sz = strlen(optarg);
726
727 if (strcmp(optarg, "list") == 0) {
728 for (a = algtab; a->name; a++)
729 printf("%-10s %s\n", a->name, a->help);
730 return (0);
731 }
732
733 alg = 0;
734 for (a = algtab; a->name; a++) {
735 if (strncmp(optarg, a->name, sz) == 0) {
736 if (a->name[sz] == 0) {
737 alg = a;
738 break;
739 } else if (alg)
740 die(EXIT_FAILURE, "ambiguous algorithm name `%s'", optarg);
741 else
742 alg = a;
743 }
744 }
745 if (!alg)
746 die(EXIT_FAILURE, "unknown algorithm name `%s'", optarg);
747 } break;
748
749 /* --- Bits must be nonzero and a multiple of 8 --- */
750
751 case 'b': {
752 char *p;
753 k.bits = strtoul(optarg, &p, 0);
754 if (k.bits == 0 || *p != 0)
755 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
756 } break;
757
758 case 'B': {
759 char *p;
760 k.qbits = strtoul(optarg, &p, 0);
761 if (k.qbits == 0 || *p != 0)
762 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
763 } break;
764
765 /* --- Parameter selection --- */
766
767 case 'p':
768 ptag = optarg;
769 break;
770
771 /* --- Expiry dates get passed to @get_date@ for parsing --- */
772
773 case 'e':
774 if (strncmp(optarg, "forever", strlen(optarg)) == 0)
775 exp = KEXP_FOREVER;
776 else {
777 exp = get_date(optarg, 0);
778 if (exp == -1)
779 die(EXIT_FAILURE, "bad expiry date `%s'", optarg);
780 }
781 break;
782
783 /* --- Store comments without interpretation --- */
784
785 case 'c':
786 if (key_chkcomment(optarg))
787 die(EXIT_FAILURE, "bad comment string `%s'", optarg);
788 c = optarg;
789 break;
790
791 /* --- Store tags --- */
792
793 case 't':
794 if (key_chkident(optarg))
795 die(EXIT_FAILURE, "bad tag string `%s'", optarg);
796 tag = optarg;
797 break;
798
799 /* --- Other flags --- */
800
801 case 'r':
802 rtag = optarg;
803 break;
804 case 'l':
805 k.f |= f_lock;
806 break;
807 case 'q':
808 k.f |= f_quiet;
809 break;
810 case 'L':
811 k.f |= f_limlee;
812 break;
813 case 'S':
814 k.f |= f_subgroup;
815 break;
816
817 /* --- Other things are bogus --- */
818
819 default:
820 k.f |= f_bogus;
821 break;
822 }
823 }
824
825 /* --- Various sorts of bogosity --- */
826
827 if ((k.f & f_bogus) || optind + 1 > argc) {
828 die(EXIT_FAILURE,
829 "Usage: add [options] type [attr...]");
830 }
831 if (key_chkident(argv[optind]))
832 die(EXIT_FAILURE, "bad key type `%s'", argv[optind]);
833
834 /* --- Set up various bits of the state --- */
835
836 if (exp == KEXP_EXPIRE)
837 exp = time(0) + 14 * 24 * 60 * 60;
838
839 /* --- Open the file and create the basic key block --- *
840 *
841 * Keep on generating keyids until one of them doesn't collide.
842 */
843
844 doopen(&f, KOPEN_WRITE);
845 k.kf = &f;
846
847 /* --- Key the generator --- */
848
849 keyrand(&f, rtag);
850
851 for (;;) {
852 uint32 id = rand_global.ops->word(&rand_global);
853 int err;
854 k.k = key_new(&f, id, argv[optind], exp, &err);
855 if (k.k)
856 break;
857 if (err != KERR_DUPID)
858 die(EXIT_FAILURE, "error adding new key: %s", key_strerror(err));
859 }
860
861 /* --- Set various simple attributes --- */
862
863 if (tag) {
864 int err = key_settag(&f, k.k, tag);
865 if (err)
866 die(EXIT_FAILURE, "error setting key tag: %s", key_strerror(err));
867 }
868
869 if (c) {
870 int err = key_setcomment(&f, k.k, c);
871 if (err)
872 die(EXIT_FAILURE, "error setting key comment: %s", key_strerror(err));
873 }
874
875 setattr(&f, k.k, argv + optind + 1);
876
877 key_fulltag(k.k, &k.tag);
878
879 /* --- Find the parameter key --- */
880
881 if (ptag) {
882 if ((k.p = key_bytag(&f, ptag)) == 0)
883 die(EXIT_FAILURE, "parameter key `%s' not found", ptag);
884 if ((k.p->k.e & KF_ENCMASK) != KENC_STRUCT)
885 die(EXIT_FAILURE, "parameter key `%s' is not structured", ptag);
886 }
887
888 /* --- Now generate the actual key data --- */
889
890 alg->proc(&k);
891
892 /* --- Done --- */
893
894 doclose(&f);
895 return (0);
896 }
897
898 /*----- Key listing -------------------------------------------------------*/
899
900 /* --- Listing options --- */
901
902 typedef struct listopts {
903 const char *tfmt; /* Date format (@strftime@-style) */
904 int v; /* Verbosity level */
905 unsigned f; /* Various flags */
906 time_t t; /* Time now (for key expiry) */
907 key_filter kf; /* Filter for matching keys */
908 } listopts;
909
910 /* --- Listing flags --- */
911
912 enum {
913 f_newline = 2, /* Write newline before next entry */
914 f_attr = 4, /* Written at least one attribute */
915 f_utc = 8 /* Emit UTC time, not local time */
916 };
917
918 /* --- @showkeydata@ --- *
919 *
920 * Arguments: @key_data *k@ = pointer to key to write
921 * @int ind@ = indentation level
922 * @listopts *o@ = listing options
923 * @dstr *d@ = tag string for this subkey
924 *
925 * Returns: ---
926 *
927 * Use: Emits a piece of key data in a human-readable format.
928 */
929
930 static void showkeydata(key_data *k, int ind, listopts *o, dstr *d)
931 {
932 #define INDENT(i) do { \
933 int _i; \
934 for (_i = 0; _i < (i); _i++) { \
935 putchar(' '); \
936 } \
937 } while (0)
938
939 switch (k->e & KF_ENCMASK) {
940
941 /* --- Binary key data --- *
942 *
943 * Emit as a simple hex dump.
944 */
945
946 case KENC_BINARY: {
947 const octet *p = k->u.k.k;
948 const octet *l = p + k->u.k.sz;
949 size_t sz = 0;
950
951 fputs(" {", stdout);
952 while (p < l) {
953 if (sz % 16 == 0) {
954 putchar('\n');
955 INDENT(ind + 2);
956 } else if (sz % 8 == 0)
957 fputs(" ", stdout);
958 else
959 putc(' ', stdout);
960 printf("%02x", *p++);
961 sz++;
962 }
963 putchar('\n');
964 INDENT(ind);
965 fputs("}\n", stdout);
966 } break;
967
968 /* --- Encrypted data --- *
969 *
970 * If the user is sufficiently keen, ask for a passphrase and decrypt the
971 * key. Otherwise just say that it's encrypted and move on.
972 */
973
974 case KENC_ENCRYPT:
975 if (o->v <= 3)
976 fputs(" encrypted\n", stdout);
977 else {
978 key_data kd;
979 if (key_punlock(d->buf, k, &kd))
980 printf(" <failed to unlock %s>\n", d->buf);
981 else {
982 fputs(" encrypted", stdout);
983 showkeydata(&kd, ind, o, d);
984 key_destroy(&kd);
985 }
986 }
987 break;
988
989 /* --- Integer keys --- *
990 *
991 * Emit as a large integer in decimal. This makes using the key in
992 * `calc' or whatever easier.
993 */
994
995 case KENC_MP:
996 putchar(' ');
997 mp_writefile(k->u.m, stdout, 10);
998 putchar('\n');
999 break;
1000
1001 /* --- Structured keys --- *
1002 *
1003 * Just iterate over the subkeys.
1004 */
1005
1006 case KENC_STRUCT: {
1007 sym_iter i;
1008 key_struct *ks;
1009 size_t n = d->len;
1010
1011 fputs(" {\n", stdout);
1012 for (sym_mkiter(&i, &k->u.s); (ks = sym_next(&i)) != 0; ) {
1013 if (!key_match(&ks->k, &o->kf))
1014 continue;
1015 INDENT(ind + 2);
1016 printf("%s =", SYM_NAME(ks));
1017 d->len = n;
1018 dstr_putf(d, ".%s", SYM_NAME(ks));
1019 showkeydata(&ks->k, ind + 2, o, d);
1020 }
1021 INDENT(ind);
1022 fputs("}\n", stdout);
1023 } break;
1024 }
1025
1026 #undef INDENT
1027 }
1028
1029 /* --- @showkey@ --- *
1030 *
1031 * Arguments: @key *k@ = pointer to key to show
1032 * @listopts *o@ = pointer to listing options
1033 *
1034 * Returns: ---
1035 *
1036 * Use: Emits a listing of a particular key.
1037 */
1038
1039 static void showkey(key *k, listopts *o)
1040 {
1041 char ebuf[24], dbuf[24];
1042 struct tm *tm;
1043
1044 /* --- Skip the key if the filter doesn't match --- */
1045
1046 if (!key_match(&k->k, &o->kf))
1047 return;
1048
1049 /* --- Sort out the expiry and deletion times --- */
1050
1051 if (KEY_EXPIRED(o->t, k->exp))
1052 strcpy(ebuf, "expired");
1053 else if (k->exp == KEXP_FOREVER)
1054 strcpy(ebuf, "forever");
1055 else {
1056 tm = (o->f & f_utc) ? gmtime(&k->exp) : localtime(&k->exp);
1057 strftime(ebuf, sizeof(ebuf), o->tfmt, tm);
1058 }
1059
1060 if (KEY_EXPIRED(o->t, k->del))
1061 strcpy(dbuf, "deleted");
1062 else if (k->del == KEXP_FOREVER)
1063 strcpy(dbuf, "forever");
1064 else {
1065 tm = (o->f & f_utc) ? gmtime(&k->del) : localtime(&k->del);
1066 strftime(dbuf, sizeof(dbuf), o->tfmt, tm);
1067 }
1068
1069 /* --- If in compact format, just display and quit --- */
1070
1071 if (!o->v) {
1072 if (!(o->f & f_newline)) {
1073 printf("%8s %-20s %-20s %-10s %-10s\n",
1074 "Id", "Tag", "Type", "Expire", "Delete");
1075 }
1076 printf("%08lx %-20s %-20s %-10s %-10s\n",
1077 (unsigned long)k->id, k->tag ? k->tag : "<none>",
1078 k->type, ebuf, dbuf);
1079 o->f |= f_newline;
1080 return;
1081 }
1082
1083 /* --- Display the standard header --- */
1084
1085 if (o->f & f_newline)
1086 fputc('\n', stdout);
1087 printf("keyid: %08lx\n", (unsigned long)k->id);
1088 printf("tag: %s\n", k->tag ? k->tag : "<none>");
1089 printf("type: %s\n", k->type);
1090 printf("expiry: %s\n", ebuf);
1091 printf("delete: %s\n", dbuf);
1092 printf("comment: %s\n", k->c ? k->c : "<none>");
1093
1094 /* --- Display the attributes --- */
1095
1096 if (o->v > 1) {
1097 key_attriter i;
1098 const char *av, *an;
1099
1100 o->f &= ~f_attr;
1101 printf("attributes:");
1102 for (key_mkattriter(&i, k); key_nextattr(&i, &an, &av); ) {
1103 printf("\n %s = %s", an, av);
1104 o->f |= f_attr;
1105 }
1106 if (o->f & f_attr)
1107 fputc('\n', stdout);
1108 else
1109 puts(" <none>");
1110 }
1111
1112 /* --- If dumping requested, dump the raw key data --- */
1113
1114 if (o->v > 2) {
1115 dstr d = DSTR_INIT;
1116 fputs("key:", stdout);
1117 key_fulltag(k, &d);
1118 showkeydata(&k->k, 0, o, &d);
1119 dstr_destroy(&d);
1120 }
1121
1122 o->f |= f_newline;
1123 }
1124
1125 /* --- @cmd_list@ --- */
1126
1127 static int cmd_list(int argc, char *argv[])
1128 {
1129 key_file f;
1130 key *k;
1131 listopts o = { 0, 0, 0, 0, { 0, 0 } };
1132
1133 /* --- Parse subcommand options --- */
1134
1135 for (;;) {
1136 static struct option opt[] = {
1137 { "quiet", 0, 0, 'q' },
1138 { "verbose", 0, 0, 'v' },
1139 { "utc", 0, 0, 'u' },
1140 { "filter", OPTF_ARGREQ, 0, 'f' },
1141 { 0, 0, 0, 0 }
1142 };
1143 int i = mdwopt(argc, argv, "+uqvf:", opt, 0, 0, 0);
1144 if (i < 0)
1145 break;
1146
1147 switch (i) {
1148 case 'u':
1149 o.f |= f_utc;
1150 break;
1151 case 'q':
1152 if (o.v)
1153 o.v--;
1154 break;
1155 case 'v':
1156 o.v++;
1157 break;
1158 case 'f': {
1159 char *p;
1160 int e = key_readflags(optarg, &p, &o.kf.f, &o.kf.m);
1161 if (e || *p)
1162 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1163 } break;
1164 default:
1165 o.f |= f_bogus;
1166 break;
1167 }
1168 }
1169
1170 if (o.f & f_bogus)
1171 die(EXIT_FAILURE, "Usage: list [-uqv] [-f filter] [tag...]");
1172
1173 /* --- Open the key file --- */
1174
1175 doopen(&f, KOPEN_READ);
1176 o.t = time(0);
1177
1178 /* --- Set up the time format --- */
1179
1180 if (!o.v)
1181 o.tfmt = "%Y-%m-%d";
1182 else if (o.f & f_utc)
1183 o.tfmt = "%Y-%m-%d %H:%M:%S UTC";
1184 else
1185 o.tfmt = "%Y-%m-%d %H:%M:%S %Z";
1186
1187 /* --- If specific keys were requested use them, otherwise do all --- *
1188 *
1189 * Some day, this might turn into a wildcard match.
1190 */
1191
1192 if (optind < argc) {
1193 do {
1194 if ((k = key_bytag(&f, argv[optind])) != 0)
1195 showkey(k, &o);
1196 else {
1197 moan("key `%s' not found", argv[optind]);
1198 o.f |= f_bogus;
1199 }
1200 optind++;
1201 } while (optind < argc);
1202 } else {
1203 key_iter i;
1204 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1205 showkey(k, &o);
1206 }
1207
1208 /* --- Done --- */
1209
1210 doclose(&f);
1211 if (o.f & f_bogus)
1212 return (EXIT_FAILURE);
1213 else
1214 return (0);
1215 }
1216
1217 /*----- Command implementation --------------------------------------------*/
1218
1219 /* --- @cmd_expire@ --- */
1220
1221 static int cmd_expire(int argc, char *argv[])
1222 {
1223 key_file f;
1224 key *k;
1225 int i;
1226 int rc = 0;
1227
1228 if (argc < 2)
1229 die(EXIT_FAILURE, "Usage: expire tag...");
1230 doopen(&f, KOPEN_WRITE);
1231 for (i = 1; i < argc; i++) {
1232 if ((k = key_bytag(&f, argv[i])) != 0)
1233 key_expire(&f, k);
1234 else {
1235 moan("key `%s' not found", argv[i]);
1236 rc = 1;
1237 }
1238 }
1239 doclose(&f);
1240 return (rc);
1241 }
1242
1243 /* --- @cmd_delete@ --- */
1244
1245 static int cmd_delete(int argc, char *argv[])
1246 {
1247 key_file f;
1248 key *k;
1249 int i;
1250 int rc = 0;
1251
1252 if (argc < 2)
1253 die(EXIT_FAILURE, "Usage: delete tag...");
1254 doopen(&f, KOPEN_WRITE);
1255 for (i = 1; i < argc; i++) {
1256 if ((k = key_bytag(&f, argv[i])) != 0)
1257 key_delete(&f, k);
1258 else {
1259 moan("key `%s' not found", argv[i]);
1260 rc = 1;
1261 }
1262 }
1263 doclose(&f);
1264 return (rc);
1265 }
1266
1267 /* --- @cmd_setattr@ --- */
1268
1269 static int cmd_setattr(int argc, char *argv[])
1270 {
1271 key_file f;
1272 key *k;
1273
1274 if (argc < 3)
1275 die(EXIT_FAILURE, "Usage: setattr tag attr...");
1276 doopen(&f, KOPEN_WRITE);
1277 if ((k = key_bytag(&f, argv[1])) == 0)
1278 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1279 setattr(&f, k, argv + 2);
1280 doclose(&f);
1281 return (0);
1282 }
1283
1284 /* --- @cmd_finger@ --- */
1285
1286 static void fingerprint(key *k, const key_filter *kf)
1287 {
1288 rmd160_ctx r;
1289 octet hash[RMD160_HASHSZ];
1290 dstr d = DSTR_INIT;
1291 int i;
1292
1293 if (!key_encode(&k->k, &d, kf))
1294 return;
1295 rmd160_init(&r);
1296 rmd160_hash(&r, d.buf, d.len);
1297 rmd160_done(&r, hash);
1298
1299 DRESET(&d);
1300 key_fulltag(k, &d);
1301 for (i = 0; i < sizeof(hash); i++) {
1302 if (i && i % 4 == 0)
1303 putchar('-');
1304 printf("%02x", hash[i]);
1305 }
1306 printf(" %s\n", d.buf);
1307 dstr_destroy(&d);
1308 }
1309
1310 static int cmd_finger(int argc, char *argv[])
1311 {
1312 key_file f;
1313 int rc = 0;
1314 key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1315
1316 for (;;) {
1317 static struct option opt[] = {
1318 { "filter", OPTF_ARGREQ, 0, 'f' },
1319 { 0, 0, 0, 0 }
1320 };
1321 int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
1322 if (i < 0)
1323 break;
1324 switch (i) {
1325 case 'f': {
1326 char *p;
1327 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1328 if (err || *p)
1329 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1330 } break;
1331 default:
1332 rc = 1;
1333 break;
1334 }
1335 }
1336
1337 argv += optind; argc -= optind;
1338 if (rc)
1339 die(EXIT_FAILURE, "Usage: fingerprint [-f filter] [tag...]");
1340
1341 doopen(&f, KOPEN_READ);
1342
1343 if (argc) {
1344 int i;
1345 for (i = 0; i < argc; i++) {
1346 key *k = key_bytag(&f, argv[i]);
1347 if (k)
1348 fingerprint(k, &kf);
1349 else {
1350 rc = 1;
1351 moan("key `%s' not found", argv[i]);
1352 }
1353 }
1354 } else {
1355 key_iter i;
1356 key *k;
1357 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1358 fingerprint(k, &kf);
1359 }
1360 return (rc);
1361 }
1362
1363 /* --- @cmd_comment@ --- */
1364
1365 static int cmd_comment(int argc, char *argv[])
1366 {
1367 key_file f;
1368 key *k;
1369 int err;
1370
1371 if (argc < 2 || argc > 3)
1372 die(EXIT_FAILURE, "Usage: comment tag [comment]");
1373 doopen(&f, KOPEN_WRITE);
1374 if ((k = key_bytag(&f, argv[1])) == 0)
1375 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1376 if ((err = key_setcomment(&f, k, argv[2])) != 0)
1377 die(EXIT_FAILURE, "bad comment `%s': %s", argv[2], key_strerror(err));
1378 doclose(&f);
1379 return (0);
1380 }
1381
1382 /* --- @cmd_tag@ --- */
1383
1384 static int cmd_tag(int argc, char *argv[])
1385 {
1386 key_file f;
1387 key *k;
1388 int err;
1389
1390 if (argc < 2 || argc > 3)
1391 die(EXIT_FAILURE, "Usage: tag tag [new-tag]");
1392 doopen(&f, KOPEN_WRITE);
1393 if ((k = key_bytag(&f, argv[1])) == 0)
1394 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1395 if ((err = key_settag(&f, k, argv[2])) != 0)
1396 die(EXIT_FAILURE, "bad tag `%s': %s", argv[2], key_strerror(err));
1397 doclose(&f);
1398 return (0);
1399 }
1400
1401 /* --- @cmd_lock@ --- */
1402
1403 static int cmd_lock(int argc, char *argv[])
1404 {
1405 key_file f;
1406 key *k;
1407 key_data *kd;
1408 dstr d = DSTR_INIT;
1409
1410 if (argc != 2)
1411 die(EXIT_FAILURE, "Usage: lock qtag");
1412 doopen(&f, KOPEN_WRITE);
1413 if (key_qtag(&f, argv[1], &d, &k, &kd))
1414 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1415 if (kd->e == KENC_ENCRYPT && key_punlock(d.buf, kd, kd))
1416 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
1417 if (key_plock(d.buf, kd, kd))
1418 die(EXIT_FAILURE, "failed to lock key `%s'", d.buf);
1419 f.f |= KF_MODIFIED;
1420 doclose(&f);
1421 return (0);
1422 }
1423
1424 /* --- @cmd_unlock@ --- */
1425
1426 static int cmd_unlock(int argc, char *argv[])
1427 {
1428 key_file f;
1429 key *k;
1430 key_data *kd;
1431 dstr d = DSTR_INIT;
1432
1433 if (argc != 2)
1434 die(EXIT_FAILURE, "Usage: unlock qtag");
1435 doopen(&f, KOPEN_WRITE);
1436 if (key_qtag(&f, argv[1], &d, &k, &kd))
1437 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1438 if (kd->e != KENC_ENCRYPT)
1439 die(EXIT_FAILURE, "key `%s' is not encrypted", d.buf);
1440 if (kd->e == KENC_ENCRYPT && key_punlock(d.buf, kd, kd))
1441 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
1442 f.f |= KF_MODIFIED;
1443 doclose(&f);
1444 return (0);
1445 }
1446
1447 /* --- @cmd_extract@ --- */
1448
1449 static int cmd_extract(int argc, char *argv[])
1450 {
1451 key_file f;
1452 key *k;
1453 int i;
1454 int rc = 0;
1455 key_filter kf = { 0, 0 };
1456 FILE *fp;
1457
1458 for (;;) {
1459 static struct option opt[] = {
1460 { "filter", OPTF_ARGREQ, 0, 'f' },
1461 { 0, 0, 0, 0 }
1462 };
1463 int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
1464 if (i < 0)
1465 break;
1466 switch (i) {
1467 case 'f': {
1468 char *p;
1469 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1470 if (err || *p)
1471 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1472 } break;
1473 default:
1474 rc = 1;
1475 break;
1476 }
1477 }
1478
1479 argv += optind; argc -= optind;
1480 if (rc || argc < 1)
1481 die(EXIT_FAILURE, "Usage: extract [-f filter] file [tag...]");
1482 if (strcmp(*argv, "-") == 0)
1483 fp = stdout;
1484 else if (!(fp = fopen(*argv, "w"))) {
1485 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
1486 *argv, strerror(errno));
1487 }
1488
1489 doopen(&f, KOPEN_READ);
1490 if (argc < 2) {
1491 key_iter i;
1492 key *k;
1493 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1494 key_extract(&f, k, fp, &kf);
1495 } else {
1496 for (i = 1; i < argc; i++) {
1497 if ((k = key_bytag(&f, argv[i])) != 0)
1498 key_extract(&f, k, fp, &kf);
1499 else {
1500 moan("key `%s' not found", argv[i]);
1501 rc = 1;
1502 }
1503 }
1504 }
1505 if (fclose(fp))
1506 die(EXIT_FAILURE, "error writing file: %s", strerror(errno));
1507 doclose(&f);
1508 return (rc);
1509 }
1510
1511 /* --- @cmd_tidy@ --- */
1512
1513 static int cmd_tidy(int argc, char *argv[])
1514 {
1515 key_file f;
1516 if (argc != 1)
1517 die(EXIT_FAILURE, "usage: tidy");
1518 doopen(&f, KOPEN_WRITE);
1519 f.f |= KF_MODIFIED; /* Nasty hack */
1520 doclose(&f);
1521 return (0);
1522 }
1523
1524 /* --- @cmd_merge@ --- */
1525
1526 static int cmd_merge(int argc, char *argv[])
1527 {
1528 key_file f;
1529 FILE *fp;
1530
1531 if (argc != 2)
1532 die(EXIT_FAILURE, "Usage: merge file");
1533 if (strcmp(argv[1], "-") == 0)
1534 fp = stdin;
1535 else if (!(fp = fopen(argv[1], "r"))) {
1536 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
1537 argv[1], strerror(errno));
1538 }
1539
1540 doopen(&f, KOPEN_WRITE);
1541 key_merge(&f, argv[1], fp, key_moan, 0);
1542 doclose(&f);
1543 return (0);
1544 }
1545
1546 /*----- Main command table ------------------------------------------------*/
1547
1548 static struct cmd {
1549 const char *name;
1550 int (*cmd)(int /*argc*/, char */*argv*/[]);
1551 const char *help;
1552 } cmds[] = {
1553 { "add", cmd_add,
1554 "add [options] type [attr...]\n\
1555 Options: [-lqLS] [-a alg] [-b|-B bits] [-p param] [-r tag]\n\
1556 [-e expire] [-t tag] [-c comment]"
1557 },
1558 { "expire", cmd_expire, "expire tag..." },
1559 { "delete", cmd_delete, "delete tag..." },
1560 { "tag", cmd_tag, "tag tag [new-tag]" },
1561 { "setattr", cmd_setattr, "setattr tag attr..." },
1562 { "comment", cmd_comment, "comment tag [comment]" },
1563 { "lock", cmd_lock, "lock qtag" },
1564 { "unlock", cmd_unlock, "unlock qtag" },
1565 { "list", cmd_list, "list [-uqv] [-f filter] [tag...]" },
1566 { "fingerprint", cmd_finger, "fingerprint [-f filter] [tag...]" },
1567 { "tidy", cmd_tidy, "tidy" },
1568 { "extract", cmd_extract, "extract [-f filter] file [tag...]" },
1569 { "merge", cmd_merge, "merge file" },
1570 { 0, 0, 0 }
1571 };
1572
1573 typedef struct cmd cmd;
1574
1575 /*----- Main code ---------------------------------------------------------*/
1576
1577 /* --- Helpful GNUy functions --- */
1578
1579 void usage(FILE *fp)
1580 {
1581 pquis(fp, "Usage: $ [-k file] [-i tag] [-t type] command [args]\n");
1582 }
1583
1584 void version(FILE *fp)
1585 {
1586 pquis(fp, "$, Catacomb version " VERSION "\n");
1587 }
1588
1589 void help(FILE *fp)
1590 {
1591 cmd *c;
1592 version(fp);
1593 fputc('\n', fp);
1594 usage(fp);
1595 fputs("\n\
1596 Performs various simple key management operations. Command line options\n\
1597 recognized are:\n\
1598 \n\
1599 -h, --help Display this help text.\n\
1600 -v, --version Display version number.\n\
1601 -u, --usage Display short usage summary.\n\
1602 \n\
1603 -k, --keyring=FILE Read and write keys in FILE.\n\
1604 -i, --id=TAG Use key TAG for random number generator.\n\
1605 -t, --type=TYPE Use key TYPE for random number generator.\n\
1606 \n\
1607 The following commands are understood:\n\n",
1608 fp);
1609 for (c = cmds; c->name; c++)
1610 fprintf(fp, "%s\n", c->help);
1611 }
1612
1613 /* --- @main@ --- *
1614 *
1615 * Arguments: @int argc@ = number of command line arguments
1616 * @char *argv[]@ = array of command line arguments
1617 *
1618 * Returns: Nonzero on failure.
1619 *
1620 * Use: Main program. Performs simple key management functions.
1621 */
1622
1623 int main(int argc, char *argv[])
1624 {
1625 unsigned f = 0;
1626
1627 enum {
1628 f_bogus = 1
1629 };
1630
1631 /* --- Initialization --- */
1632
1633 ego(argv[0]);
1634 sub_init();
1635
1636 /* --- Parse command line options --- */
1637
1638 for (;;) {
1639 static struct option opt[] = {
1640
1641 /* --- Standard GNUy help options --- */
1642
1643 { "help", 0, 0, 'h' },
1644 { "version", 0, 0, 'v' },
1645 { "usage", 0, 0, 'u' },
1646
1647 /* --- Real live useful options --- */
1648
1649 { "keyring", OPTF_ARGREQ, 0, 'k' },
1650 { "id", OPTF_ARGREQ, 0, 'i' },
1651 { "type", OPTF_ARGREQ, 0, 't' },
1652
1653 /* --- Magic terminator --- */
1654
1655 { 0, 0, 0, 0 }
1656 };
1657 int i = mdwopt(argc, argv, "+hvu k:i:t:", opt, 0, 0, 0);
1658
1659 if (i < 0)
1660 break;
1661 switch (i) {
1662
1663 /* --- GNU help options --- */
1664 case 'h':
1665 help(stdout);
1666 exit(0);
1667 case 'v':
1668 version(stdout);
1669 exit(0);
1670 case 'u':
1671 usage(stdout);
1672 exit(0);
1673
1674 /* --- Real useful options --- */
1675
1676 case 'k':
1677 keyfile = optarg;
1678 break;
1679
1680 /* --- Bogosity --- */
1681
1682 default:
1683 f |= f_bogus;
1684 break;
1685 }
1686 }
1687
1688 /* --- Complain about excessive bogons --- */
1689
1690 if (f & f_bogus || optind == argc) {
1691 usage(stderr);
1692 exit(1);
1693 }
1694
1695 /* --- Initialize the Catacomb random number generator --- */
1696
1697 rand_noisesrc(RAND_GLOBAL, &noise_source);
1698 rand_seed(RAND_GLOBAL, 160);
1699
1700 /* --- Dispatch to appropriate command handler --- */
1701
1702 argc -= optind;
1703 argv += optind;
1704 optind = 0;
1705
1706 {
1707 cmd *c, *chosen = 0;
1708 size_t sz = strlen(argv[0]);
1709
1710 for (c = cmds; c->name; c++) {
1711 if (strncmp(argv[0], c->name, sz) == 0) {
1712 if (c->name[sz] == 0) {
1713 chosen = c;
1714 break;
1715 } else if (chosen)
1716 die(EXIT_FAILURE, "ambiguous command name `%s'", argv[0]);
1717 else
1718 chosen = c;
1719 }
1720 }
1721 if (!chosen)
1722 die(EXIT_FAILURE, "unknown command name `%s'", argv[0]);
1723 return (chosen->cmd(argc, argv));
1724 }
1725 }
1726
1727 /*----- That's all, folks -------------------------------------------------*/