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