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