chiark / gitweb /
mpint: Fix misbehaviour on larger-than-mpw integer types.
[catacomb] / keyutil.c
1 /* -*-c-*-
2  *
3  * $Id$
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 /*----- Header files ------------------------------------------------------*/
31
32 #include "config.h"
33
34 #include <ctype.h>
35 #include <errno.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <time.h>
40
41 #include <mLib/base64.h>
42 #include <mLib/mdwopt.h>
43 #include <mLib/quis.h>
44 #include <mLib/report.h>
45 #include <mLib/sub.h>
46
47 #include <noise.h>
48 #include <rand.h>
49
50 #include "bintab.h"
51 #include "bbs.h"
52 #include "dh.h"
53 #include "dsa.h"
54 #include "dsarand.h"
55 #include "ec.h"
56 #include "ec-keys.h"
57 #include "ectab.h"
58 #include "fibrand.h"
59 #include "getdate.h"
60 #include "gfreduce.h"
61 #include "key.h"
62 #include "mp.h"
63 #include "mpmont.h"
64 #include "mprand.h"
65 #include "mptext.h"
66 #include "pgen.h"
67 #include "ptab.h"
68 #include "rsa.h"
69
70 #include "cc.h"
71 #include "sha-mgf.h"
72 #include "sha256-mgf.h"
73 #include "sha224-mgf.h"
74 #include "sha384-mgf.h"
75 #include "sha512-mgf.h"
76 #include "tiger-mgf.h"
77 #include "rmd128-mgf.h"
78 #include "rmd160-mgf.h"
79 #include "rmd256-mgf.h"
80 #include "rmd320-mgf.h"
81 #include "md5-mgf.h"
82 #include "dsarand.h"
83
84 /*----- Handy global state ------------------------------------------------*/
85
86 static const char *keyfile = "keyring";
87
88 /*----- Useful shared functions -------------------------------------------*/
89
90 /* --- @doopen@ --- *
91  *
92  * Arguments:   @key_file *f@ = pointer to key file block
93  *              @unsigned how@ = method to open file with
94  *
95  * Returns:     ---
96  *
97  * Use:         Opens a key file and handles errors by panicking
98  *              appropriately.
99  */
100
101 static void doopen(key_file *f, unsigned how)
102 {
103   if (key_open(f, keyfile, how, key_moan, 0))
104     die(1, "couldn't open keyring `%s': %s", keyfile, strerror(errno));
105 }
106
107 /* --- @doclose@ --- *
108  *
109  * Arguments:   @key_file *f@ = pointer to key file block
110  *
111  * Returns:     ---
112  *
113  * Use:         Closes a key file and handles errors by panicking
114  *              appropriately.
115  */
116
117 static void doclose(key_file *f)
118 {
119   switch (key_close(f)) {
120     case KWRITE_FAIL:
121       die(EXIT_FAILURE, "couldn't write file `%s': %s",
122           keyfile, strerror(errno));
123     case KWRITE_BROKEN:
124       die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
125           keyfile, strerror(errno));
126   }
127 }
128
129 /* --- @setattr@ --- *
130  *
131  * Arguments:   @key_file *f@ = pointer to key file block
132  *              @key *k@ = pointer to key block
133  *              @char *v[]@ = array of assignments (overwritten!)
134  *
135  * Returns:     ---
136  *
137  * Use:         Applies the attribute assignments to the key.
138  */
139
140 static void setattr(key_file *f, key *k, char *v[])
141 {
142   while (*v) {
143     int err;
144     char *p = *v;
145     size_t eq = strcspn(p, "=");
146     if (!p[eq]) {
147       moan("invalid assignment: `%s' (ignored)", p);
148       v++;
149       continue;
150     }
151     p[eq] = 0;
152     p += eq + 1;
153     if ((err = key_putattr(f, k, *v, *p ? p : 0)) != 0)
154       die(EXIT_FAILURE, "couldn't set attributes: %s", key_strerror(err));
155     v++;
156   }
157 }
158
159 /*----- Seeding -----------------------------------------------------------*/
160
161 const struct seedalg { const char *p; grand *(*gen)(const void *, size_t); }
162 seedtab[] = {
163   { "dsarand",  dsarand_create },
164   { "rmd128-mgf",  rmd128_mgfrand },
165   { "rmd160-mgf",  rmd160_mgfrand },
166   { "rmd256-mgf",  rmd256_mgfrand },
167   { "rmd320-mgf",  rmd320_mgfrand },
168   { "sha-mgf",  sha_mgfrand },
169   { "sha224-mgf",  sha224_mgfrand },
170   { "sha256-mgf",  sha256_mgfrand },
171   { "sha384-mgf",  sha384_mgfrand },
172   { "sha512-mgf",  sha512_mgfrand },
173   { "tiger-mgf",  tiger_mgfrand },
174   { 0, 0 }
175 };
176
177 #define SEEDALG_DEFAULT (seedtab + 2)
178
179 /*----- Key generation ----------------------------------------------------*/
180
181 /* --- Key generation parameters --- */
182
183 typedef struct keyopts {
184   key_file *kf;                         /* Pointer to key file */
185   key *k;                               /* Pointer to the actual key */
186   dstr tag;                             /* Full tag name for the key */
187   unsigned f;                           /* Flags for the new key */
188   unsigned bits, qbits;                 /* Bit length for the new key */
189   const char *curve;                    /* Elliptic curve name/info */
190   grand *r;                             /* Random number source */
191   key *p;                               /* Parameters key-data */
192 } keyopts;
193
194 #define f_bogus 1u                      /* Error in parsing */
195 #define f_lock 2u                       /* Passphrase-lock private key */
196 #define f_quiet 4u                      /* Don't show a progress indicator */
197 #define f_limlee 8u                     /* Generate Lim-Lee primes */
198 #define f_subgroup 16u                  /* Generate a subgroup */
199 #define f_retag 32u                     /* Remove any existing tag */
200 #define f_kcdsa 64u                     /* Generate KCDSA primes */
201
202 /* --- @dolock@ --- *
203  *
204  * Arguments:   @keyopts *k@ = key generation options
205  *              @key_data **kd@ = pointer to key data to lock
206  *              @const char *t@ = tag suffix or null
207  *
208  * Returns:     ---
209  *
210  * Use:         Does passphrase locking on new keys.
211  */
212
213 static void dolock(keyopts *k, key_data **kd, const char *t)
214 {
215   if (!(k->f & f_lock))
216     return;
217   if (t)
218     dstr_putf(&k->tag, ".%s", t);
219   if (key_plock(kd, 0, k->tag.buf))
220     die(EXIT_FAILURE, "couldn't lock key");
221 }
222
223 /* --- @copyparam@ --- *
224  *
225  * Arguments:   @keyopts *k@ = pointer to key options
226  *              @const char **pp@ = checklist of parameters
227  *
228  * Returns:     Nonzero if parameters copied; zero if you have to generate
229  *              them.
230  *
231  * Use:         Copies parameters from a source key to the current one.
232  */
233
234 static int copyparam(keyopts *k, const char **pp)
235 {
236   key_filter kf;
237   key_attriter i;
238   const char *n, *v;
239
240   /* --- Quick check if no parameters supplied --- */
241
242   if (!k->p)
243     return (0);
244
245   /* --- Run through the checklist --- */
246
247   while (*pp) {
248     key_data *kd = key_structfind(k->p->k, *pp);
249     if (!kd)
250       die(EXIT_FAILURE, "bad parameter key: parameter `%s' not found", *pp);
251     if ((kd->e & KF_CATMASK) != KCAT_SHARE)
252       die(EXIT_FAILURE, "bad parameter key: subkey `%s' is not shared", *pp);
253     pp++;
254   }
255
256   /* --- Copy over the parameters --- */
257
258   kf.f = KCAT_SHARE;
259   kf.m = KF_CATMASK;
260   key_setkeydata(k->kf, k->k, k->p->k);
261
262   /* --- Copy over attributes --- */
263
264   for (key_mkattriter(&i, k->p); key_nextattr(&i, &n, &v); )
265     key_putattr(k->kf, k->k, n, v);
266
267   /* --- Done --- */
268
269   return (1);
270 }
271
272 /* --- @getmp@ --- *
273  *
274  * Arguments:   @key_data *k@ = pointer to key data block
275  *              @const char *tag@ = tag string to use
276  *
277  * Returns:     Pointer to multiprecision integer key item.
278  *
279  * Use:         Fetches an MP key component.
280  */
281
282 static mp *getmp(key_data *k, const char *tag)
283 {
284   k = key_structfind(k, tag);
285   if (!k)
286     die(EXIT_FAILURE, "unexpected failure looking up subkey `%s'", tag);
287   if ((k->e & KF_ENCMASK) != KENC_MP)
288     die(EXIT_FAILURE, "subkey `%s' has an incompatible type");
289   return (k->u.m);
290 }
291
292 /* --- @keyrand@ --- *
293  *
294  * Arguments:   @key_file *kf@ = pointer to key file
295  *              @const char *id@ = pointer to key id (or null)
296  *
297  * Returns:     ---
298  *
299  * Use:         Keys the random number generator.
300  */
301
302 static void keyrand(key_file *kf, const char *id)
303 {
304   key *k;
305
306   /* --- Find the key --- */
307
308   if (id) {
309     if ((k = key_bytag(kf, id)) == 0)
310       die(EXIT_FAILURE, "key `%s' not found", id);
311   } else
312     k = key_bytype(kf, "catacomb-rand");
313
314   if (k) {
315     key_data *kd = k->k, *kkd;
316     key_incref(kd);
317
318   again:
319     switch (kd->e & KF_ENCMASK) {
320       case KENC_BINARY:
321         break;
322       case KENC_ENCRYPT: {
323         dstr d = DSTR_INIT;
324         key_fulltag(k, &d);
325         if (key_punlock(&kkd, kd, d.buf))
326           die(EXIT_FAILURE, "error unlocking key `%s'", d.buf);
327         dstr_destroy(&d);
328         key_drop(kd);
329         kd = kkd;
330       } goto again;
331       default: {
332         dstr d = DSTR_INIT;
333         key_fulltag(k, &d);
334         die(EXIT_FAILURE, "bad encoding type for key `%s'", d.buf);
335       } break;
336     }
337
338     /* --- Key the generator --- */
339
340     rand_key(RAND_GLOBAL, kd->u.k.k, kd->u.k.sz);
341     key_drop(kd);
342   }
343 }
344
345 /* --- Key generation algorithms --- */
346
347 static void alg_binary(keyopts *k)
348 {
349   unsigned sz;
350   unsigned m;
351   key_data *kd;
352   octet *p;
353
354   if (!k->bits)
355     k->bits = 128;
356   if (k->p)
357     die(EXIT_FAILURE, "no shared parameters for binary keys");
358
359   sz = (k->bits + 7) >> 3;
360   p = sub_alloc(sz);
361   m = (1 << (((k->bits - 1) & 7) + 1)) - 1;
362   k->r->ops->fill(k->r, p, sz);
363   *p &= m;
364   kd = key_newbinary(KCAT_SYMM | KF_BURN, p, sz);
365   memset(p, 0, sz);
366   dolock(k, &kd, 0);
367   key_setkeydata(k->kf, k->k, kd);
368   key_drop(kd);
369   sub_free(p, sz);
370 }
371
372 static void alg_des(keyopts *k)
373 {
374   unsigned sz;
375   octet *p;
376   key_data *kd;
377   int i;
378
379   if (!k->bits)
380     k->bits = 168;
381   if (k->p)
382     die(EXIT_FAILURE, "no shared parameters for DES keys");
383   if (k->bits % 56 || k->bits > 168)
384     die(EXIT_FAILURE, "DES keys must be 56, 112 or 168 bits long");
385
386   sz = k->bits / 7;
387   p = sub_alloc(sz);
388   k->r->ops->fill(k->r, p, sz);
389   for (i = 0; i < sz; i++) {
390     octet x = p[i] | 0x01;
391     x = x ^ (x >> 4);
392     x = x ^ (x >> 2);
393     x = x ^ (x >> 1);
394     p[i] = (p[i] & 0xfe) | (x & 0x01);
395   }
396   kd = key_newbinary(KCAT_SYMM | KF_BURN, p, sz);
397   memset(p, 0, sz);
398   dolock(k, &kd, 0);
399   key_setkeydata(k->kf, k->k, kd);
400   key_drop(kd);
401   sub_free(p, sz);
402 }
403
404 static void alg_rsa(keyopts *k)
405 {
406   rsa_priv rp;
407   key_data *kd, *kkd;
408
409   /* --- Sanity checking --- */
410
411   if (k->p)
412     die(EXIT_FAILURE, "no shared parameters for RSA keys");
413   if (!k->bits)
414     k->bits = 1024;
415
416   /* --- Generate the RSA parameters --- */
417
418   if (rsa_gen(&rp, k->bits, k->r, 0,
419               (k->f & f_quiet) ? 0 : pgen_ev, 0))
420     die(EXIT_FAILURE, "RSA key generation failed");
421
422   /* --- Run a test encryption --- */
423
424   {
425     grand *g = fibrand_create(k->r->ops->word(k->r));
426     rsa_pub rpp;
427     mp *m = mprand_range(MP_NEW, rp.n, g, 0);
428     mp *c;
429
430     rpp.n = rp.n;
431     rpp.e = rp.e;
432     c = rsa_qpubop(&rpp, MP_NEW, m);
433     c = rsa_qprivop(&rp, c, c, g);
434
435     if (!MP_EQ(c, m))
436       die(EXIT_FAILURE, "test encryption failed");
437     mp_drop(c);
438     mp_drop(m);
439     g->ops->destroy(g);
440   }
441
442   /* --- Allrighty then --- */
443
444   kd = key_newstruct();
445   key_structsteal(kd, "n", key_newmp(KCAT_PUB, rp.n));
446   key_structsteal(kd, "e", key_newmp(KCAT_PUB, rp.e));
447
448   kkd = key_newstruct();
449   key_structsteal(kkd, "d", key_newmp(KCAT_PRIV | KF_BURN, rp.d));
450   key_structsteal(kkd, "p", key_newmp(KCAT_PRIV | KF_BURN, rp.p));
451   key_structsteal(kkd, "q", key_newmp(KCAT_PRIV | KF_BURN, rp.q));
452   key_structsteal(kkd, "q-inv", key_newmp(KCAT_PRIV | KF_BURN, rp.q_inv));
453   key_structsteal(kkd, "d-mod-p", key_newmp(KCAT_PRIV | KF_BURN, rp.dp));
454   key_structsteal(kkd, "d-mod-q", key_newmp(KCAT_PRIV | KF_BURN, rp.dq));
455   dolock(k, &kkd, "private");
456   key_structsteal(kd, "private", kkd);
457   key_setkeydata(k->kf, k->k, kd);
458   key_drop(kd);
459   rsa_privfree(&rp);
460 }
461
462 static void alg_dsaparam(keyopts *k)
463 {
464   static const char *pl[] = { "q", "p", "g", 0 };
465   if (!copyparam(k, pl)) {
466     dsa_param dp;
467     octet *p;
468     size_t sz;
469     dstr d = DSTR_INIT;
470     base64_ctx c;
471     key_data *kd;
472     dsa_seed ds;
473
474     /* --- Choose appropriate bit lengths if necessary --- */
475
476     if (!k->qbits)
477       k->qbits = 160;
478     if (!k->bits)
479       k->bits = 1024;
480
481     /* --- Allocate a seed block --- */
482
483     sz = (k->qbits + 7) >> 3;
484     p = sub_alloc(sz);
485     k->r->ops->fill(k->r, p, sz);
486
487     /* --- Allocate the parameters --- */
488
489     if (dsa_gen(&dp, k->qbits, k->bits, 0, p, sz, &ds,
490                 (k->f & f_quiet) ? 0 : pgen_ev, 0))
491       die(EXIT_FAILURE, "DSA parameter generation failed");
492
493     /* --- Store the parameters --- */
494
495     kd = key_newstruct();
496     key_structsteal(kd, "q", key_newmp(KCAT_SHARE, dp.q));
497     key_structsteal(kd, "p", key_newmp(KCAT_SHARE, dp.p));
498     key_structsteal(kd, "g", key_newmp(KCAT_SHARE, dp.g));
499     mp_drop(dp.q);
500     mp_drop(dp.p);
501     mp_drop(dp.g);
502     key_setkeydata(k->kf, k->k, kd);
503     key_drop(kd);
504
505     /* --- Store the seed for future verification --- */
506
507     base64_init(&c);
508     c.maxline = 0;
509     c.indent = "";
510     base64_encode(&c, ds.p, ds.sz, &d);
511     base64_encode(&c, 0, 0, &d);
512     DPUTZ(&d);
513     key_putattr(k->kf, k->k, "seed", d.buf);
514     DRESET(&d);
515     dstr_putf(&d, "%u", ds.count);
516     key_putattr(k->kf, k->k, "count", d.buf);
517     xfree(ds.p);
518     sub_free(p, sz);
519     dstr_destroy(&d);
520   }
521 }
522
523 static void alg_dsa(keyopts *k)
524 {
525   mp *q, *p, *g;
526   mp *x, *y;
527   mpmont mm;
528   key_data *kd, *kkd;
529
530   /* --- Get the shared parameters --- */
531
532   alg_dsaparam(k);
533   key_split(&k->k->k); kd = k->k->k;
534   q = getmp(kd, "q");
535   p = getmp(kd, "p");
536   g = getmp(kd, "g");
537
538   /* --- Choose a private key --- */
539
540   x = mprand_range(MP_NEWSEC, q, k->r, 0);
541   mpmont_create(&mm, p);
542   y = mpmont_exp(&mm, MP_NEW, g, x);
543
544   /* --- Store everything away --- */
545
546   key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
547
548   kkd = key_newstruct();
549   key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
550   dolock(k, &kkd, "private");
551   key_structsteal(kd, "private", kkd);
552
553   mp_drop(x); mp_drop(y);
554 }
555
556 static void alg_dhparam(keyopts *k)
557 {
558   static const char *pl[] = { "p", "q", "g", 0 };
559   key_data *kd;
560   if (!copyparam(k, pl)) {
561     dh_param dp;
562     int rc;
563
564     if (k->curve) {
565       qd_parse qd;
566       group *g;
567       const char *e;
568       
569       if (strcmp(k->curve, "list") == 0) {
570         unsigned i, w;
571         LIST("Built-in prime fields", stdout, ptab[i].name, ptab[i].name);
572         exit(0);
573       }
574       qd.p = k->curve;
575       if (dh_parse(&qd, &dp))
576         die(EXIT_FAILURE, "error in field spec: %s", qd.e);
577       if (!qd_eofp(&qd))
578         die(EXIT_FAILURE, "junk at end of field spec");
579       if ((g = group_prime(&dp)) == 0)
580         die(EXIT_FAILURE, "invalid prime field");
581       if (!(k->f & f_quiet) && (e = G_CHECK(g, &rand_global)) != 0)
582         moan("WARNING!  group check failed: %s", e);
583       G_DESTROYGROUP(g);
584       goto done;
585     }
586     
587     if (!k->bits)
588       k->bits = 1024;
589
590     /* --- Choose a large safe prime number --- */
591
592     if (k->f & f_limlee) {
593       mp **f;
594       size_t nf;
595       if (!k->qbits)
596         k->qbits = 256;
597       rc = dh_limlee(&dp, k->qbits, k->bits,
598                      (k->f & f_subgroup) ? DH_SUBGROUP : 0,
599                      0, k->r, (k->f & f_quiet) ? 0 : pgen_ev, 0,
600                      (k->f & f_quiet) ? 0 : pgen_evspin, 0, &nf, &f);
601       if (!rc) {
602         dstr d = DSTR_INIT;
603         size_t i;
604         for (i = 0; i < nf; i++) {
605           if (i)
606             dstr_puts(&d, ", ");
607           mp_writedstr(f[i], &d, 10);
608           mp_drop(f[i]);
609         }
610         key_putattr(k->kf, k->k, "factors", d.buf);
611         dstr_destroy(&d);
612       }
613     } else if (k->f & f_kcdsa) {
614       if (!k->qbits)
615         k->qbits = 256;
616       rc = dh_kcdsagen(&dp, k->qbits, k->bits, 0,
617                        0, k->r, (k->f & f_quiet) ? 0 : pgen_ev, 0);
618       if (!rc) {
619         dstr d = DSTR_INIT;
620         mp *v = MP_NEW;
621
622         mp_writedstr(dp.q, &d, 10);
623         mp_div(&v, 0, dp.p, dp.q);
624         v = mp_lsr(v, v, 1);
625         dstr_puts(&d, ", ");
626         mp_writedstr(v, &d, 10);
627         mp_drop(v);
628         key_putattr(k->kf, k->k, "factors", d.buf);
629         dstr_destroy(&d);
630       }
631     } else
632       rc = dh_gen(&dp, k->qbits, k->bits, 0, k->r,
633                   (k->f & f_quiet) ? 0 : pgen_ev, 0);
634
635     if (rc)
636       die(EXIT_FAILURE, "Diffie-Hellman parameter generation failed");
637
638   done:
639     kd = key_newstruct();
640     key_structsteal(kd, "p", key_newmp(KCAT_SHARE, dp.p));
641     key_structsteal(kd, "q", key_newmp(KCAT_SHARE, dp.q));
642     key_structsteal(kd, "g", key_newmp(KCAT_SHARE, dp.g));
643     mp_drop(dp.q);
644     mp_drop(dp.p);
645     mp_drop(dp.g);
646     key_setkeydata(k->kf, k->k, kd);
647     key_drop(kd);
648   }
649 }
650
651 static void alg_dh(keyopts *k)
652 {
653   mp *x, *y;
654   mp *p, *q, *g;
655   mpmont mm;
656   key_data *kd, *kkd;
657
658   /* --- Get the shared parameters --- */
659
660   alg_dhparam(k);
661   key_split(&k->k->k); kd = k->k->k;
662   p = getmp(kd, "p");
663   q = getmp(kd, "q");
664   g = getmp(kd, "g");
665
666   /* --- Choose a suitable private key --- *
667    *
668    * Since %$g$% has order %$q$%, choose %$x < q$%.
669    */
670
671   x = mprand_range(MP_NEWSEC, q, k->r, 0);
672
673   /* --- Compute the public key %$y = g^x \bmod p$% --- */
674
675   mpmont_create(&mm, p);
676   y = mpmont_exp(&mm, MP_NEW, g, x);
677   mpmont_destroy(&mm);
678
679   /* --- Store everything away --- */
680
681   key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
682
683   kkd = key_newstruct();
684   key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
685   dolock(k, &kkd, "private");
686   key_structsteal(kd, "private", kkd);
687
688   mp_drop(x); mp_drop(y);
689 }
690
691 static void alg_bbs(keyopts *k)
692 {
693   bbs_priv bp;
694   key_data *kd, *kkd;
695
696   /* --- Sanity checking --- */
697
698   if (k->p)
699     die(EXIT_FAILURE, "no shared parameters for Blum-Blum-Shub keys");
700   if (!k->bits)
701     k->bits = 1024;
702
703   /* --- Generate the BBS parameters --- */
704
705   if (bbs_gen(&bp, k->bits, k->r, 0,
706               (k->f & f_quiet) ? 0 : pgen_ev, 0))
707     die(EXIT_FAILURE, "Blum-Blum-Shub key generation failed");
708
709   /* --- Allrighty then --- */
710
711   kd = key_newstruct();
712   key_structsteal(kd, "n", key_newmp(KCAT_PUB, bp.n));
713
714   kkd = key_newstruct();
715   key_structsteal(kkd, "p", key_newmp(KCAT_PRIV | KF_BURN, bp.p));
716   key_structsteal(kkd, "q", key_newmp(KCAT_PRIV | KF_BURN, bp.q));
717   dolock(k, &kkd, "private");
718   key_structsteal(kd, "private", kkd);
719   key_setkeydata(k->kf, k->k, kd);
720   key_drop(kd);
721
722   bbs_privfree(&bp);
723 }
724
725 static void alg_binparam(keyopts *k)
726 {
727   static const char *pl[] = { "p", "q", "g", 0 };
728   if (!copyparam(k, pl)) {
729     gbin_param gb;
730     qd_parse qd;
731     group *g;
732     const char *e;
733     key_data *kd;
734
735     /* --- Decide on a field --- */
736
737     if (!k->bits) k->bits = 128;
738     if (k->curve && strcmp(k->curve, "list") == 0) {
739       unsigned i, w;
740       LIST("Built-in binary fields", stdout,
741            bintab[i].name, bintab[i].name);
742       exit(0);
743     }
744     if (!k->curve) {
745       if (k->bits <= 40) k->curve = "p1363-40";
746       else if (k->bits <= 56) k->curve = "p1363-56";
747       else if (k->bits <= 64) k->curve = "p1363-64";
748       else if (k->bits <= 80) k->curve = "p1363-80";
749       else if (k->bits <= 112) k->curve = "p1363-112";
750       else if (k->bits <= 128) k->curve = "p1363-128";
751       else {
752         die(EXIT_FAILURE,
753             "no built-in binary fields provide %u-bit security",
754             k->bits);
755       }
756     }
757
758     /* --- Check it --- */
759
760     qd.e = 0;
761     qd.p = k->curve;
762     if (dhbin_parse(&qd, &gb))
763       die(EXIT_FAILURE, "error in field spec: %s", qd.e);
764     if (!qd_eofp(&qd))
765       die(EXIT_FAILURE, "junk at end of field spec");
766     if ((g = group_binary(&gb)) == 0)
767       die(EXIT_FAILURE, "invalid binary field");
768     if (!(k->f & f_quiet) && (e = G_CHECK(g, &rand_global)) != 0)
769       moan("WARNING!  group check failed: %s", e);
770     G_DESTROYGROUP(g);
771
772     /* --- Write out the answer --- */
773
774     kd = key_newstruct();
775     key_structsteal(kd, "p", key_newmp(KCAT_SHARE, gb.p));
776     key_structsteal(kd, "q", key_newmp(KCAT_SHARE, gb.q));
777     key_structsteal(kd, "g", key_newmp(KCAT_SHARE, gb.g));
778     mp_drop(gb.q);
779     mp_drop(gb.p);
780     mp_drop(gb.g);
781     key_setkeydata(k->kf, k->k, kd);
782     key_drop(kd);
783   }
784 }
785
786 static void alg_bin(keyopts *k)
787 {
788   mp *x, *y;
789   mp *p, *q, *g;
790   gfreduce r;
791   key_data *kd, *kkd;
792
793   /* --- Get the shared parameters --- */
794
795   alg_binparam(k);
796   key_split(&k->k->k); kd = k->k->k;
797   p = getmp(kd, "p");
798   q = getmp(kd, "q");
799   g = getmp(kd, "g");
800
801   /* --- Choose a suitable private key --- *
802    *
803    * Since %$g$% has order %$q$%, choose %$x < q$%.
804    */
805
806   x = mprand_range(MP_NEWSEC, q, k->r, 0);
807
808   /* --- Compute the public key %$y = g^x \bmod p$% --- */
809
810   gfreduce_create(&r, p);
811   y = gfreduce_exp(&r, MP_NEW, g, x);
812   gfreduce_destroy(&r);
813
814   /* --- Store everything away --- */
815
816   key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
817
818   kkd = key_newstruct();
819   key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
820   dolock(k, &kkd, "private");
821   key_structsteal(kd, "private", kkd);
822
823   mp_drop(x); mp_drop(y);
824 }
825
826 static void alg_ecparam(keyopts *k)
827 {
828   static const char *pl[] = { "curve", 0 };
829   if (!copyparam(k, pl)) {
830     ec_info ei;
831     const char *e;
832     key_data *kd;
833
834     /* --- Decide on a curve --- */
835
836     if (!k->bits) k->bits = 256;
837     if (k->curve && strcmp(k->curve, "list") == 0) {
838       unsigned i, w;
839       LIST("Built-in elliptic curves", stdout,
840            ectab[i].name, ectab[i].name);
841       exit(0);
842     }
843     if (!k->curve) {
844       if (k->bits <= 56) k->curve = "secp112r1";
845       else if (k->bits <= 64) k->curve = "secp128r1";
846       else if (k->bits <= 80) k->curve = "secp160r1";
847       else if (k->bits <= 96) k->curve = "secp192r1";
848       else if (k->bits <= 112) k->curve = "secp224r1";
849       else if (k->bits <= 128) k->curve = "secp256r1";
850       else if (k->bits <= 192) k->curve = "secp384r1";
851       else if (k->bits <= 256) k->curve = "secp521r1";
852       else
853         die(EXIT_FAILURE, "no built-in curves provide %u-bit security",
854             k->bits);
855     }
856
857     /* --- Check it --- */
858
859     if ((e = ec_getinfo(&ei, k->curve)) != 0)
860       die(EXIT_FAILURE, "error in curve spec: %s", e);
861     if (!(k->f & f_quiet) && (e = ec_checkinfo(&ei, k->r)) != 0)
862       moan("WARNING!  curve check failed: %s", e);
863     ec_freeinfo(&ei);
864
865     /* --- Write out the answer --- */
866
867     kd = key_newstruct();
868     key_structsteal(kd, "curve", key_newstring(KCAT_SHARE, k->curve));
869     key_setkeydata(k->kf, k->k, kd);
870     key_drop(kd);
871   }
872 }
873
874 static void alg_ec(keyopts *k)
875 {
876   key_data *kd;
877   key_data *kkd;
878   mp *x = MP_NEW;
879   ec p = EC_INIT;
880   const char *e;
881   ec_info ei;
882
883   /* --- Get the curve --- */
884
885   alg_ecparam(k);
886   key_split(&k->k->k); kd = k->k->k;
887   if ((kkd = key_structfind(kd, "curve")) == 0)
888     die(EXIT_FAILURE, "unexpected failure looking up subkey `curve')");
889   if ((kkd->e & KF_ENCMASK) != KENC_STRING)
890     die(EXIT_FAILURE, "subkey `curve' is not a string");
891   if ((e = ec_getinfo(&ei, kkd->u.p)) != 0)
892     die(EXIT_FAILURE, "error in curve spec: %s", e);
893
894   /* --- Invent a private exponent and compute the public key --- */
895
896   x = mprand_range(MP_NEWSEC, ei.r, k->r, 0);
897   ec_mul(ei.c, &p, &ei.g, x);
898
899   /* --- Store everything away --- */
900
901   key_structsteal(kd, "p", key_newec(KCAT_PUB, &p));
902
903   kkd = key_newstruct();
904   key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
905   dolock(k, &kkd, "private");
906   key_structsteal(kd, "private", kkd);
907
908   /* --- Done --- */
909
910   ec_freeinfo(&ei);
911   mp_drop(x);
912 }
913
914 /* --- The algorithm tables --- */
915
916 typedef struct keyalg {
917   const char *name;
918   void (*proc)(keyopts *o);
919   const char *help;
920 } keyalg;
921
922 static keyalg algtab[] = {
923   { "binary",           alg_binary,     "Plain binary data" },
924   { "des",              alg_des,        "Binary with DES-style parity" },
925   { "rsa",              alg_rsa,        "RSA public-key encryption" },
926   { "bbs",              alg_bbs,        "Blum-Blum-Shub generator" },
927   { "dsa",              alg_dsa,        "DSA digital signatures" },
928   { "dsa-param",        alg_dsaparam,   "DSA shared parameters" },
929   { "dh",               alg_dh,         "Diffie-Hellman key exchange" },
930   { "dh-param",         alg_dhparam,    "Diffie-Hellman parameters" },
931   { "bindh",            alg_bin,        "DH over a binary field" },
932   { "bindh-param",      alg_binparam,   "Binary-field DH parameters" },
933   { "ec-param",         alg_ecparam,    "Elliptic curve parameters" },
934   { "ec",               alg_ec,         "Elliptic curve crypto" },
935   { 0,                  0 }
936 };
937
938 /* --- @cmd_add@ --- */
939
940 static int cmd_add(int argc, char *argv[])
941 {
942   key_file f;
943   time_t exp = KEXP_EXPIRE;
944   const char *tag = 0, *ptag = 0;
945   const char *c = 0;
946   keyalg *alg = algtab;
947   const char *rtag = 0;
948   const struct seedalg *sa = SEEDALG_DEFAULT;
949   keyopts k = { 0, 0, DSTR_INIT, 0, 0, 0, 0, 0 };
950   const char *seed = 0;
951   k.r = &rand_global;
952
953   /* --- Parse options for the subcommand --- */
954
955   for (;;) {
956     static struct option opt[] = {
957       { "algorithm",    OPTF_ARGREQ,    0,      'a' },
958       { "bits",         OPTF_ARGREQ,    0,      'b' },
959       { "qbits",        OPTF_ARGREQ,    0,      'B' },
960       { "parameters",   OPTF_ARGREQ,    0,      'p' },
961       { "expire",       OPTF_ARGREQ,    0,      'e' },
962       { "comment",      OPTF_ARGREQ,    0,      'c' },
963       { "tag",          OPTF_ARGREQ,    0,      't' },
964       { "rand-id",      OPTF_ARGREQ,    0,      'R' },
965       { "curve",        OPTF_ARGREQ,    0,      'C' },
966       { "seedalg",      OPTF_ARGREQ,    0,      'A' },
967       { "seed",         OPTF_ARGREQ,    0,      's' },
968       { "newseed",      OPTF_ARGREQ,    0,      'n' },
969       { "lock",         0,              0,      'l' },
970       { "quiet",        0,              0,      'q' },
971       { "lim-lee",      0,              0,      'L' },
972       { "subgroup",     0,              0,      'S' },
973       { "kcdsa",        0,              0,      'K' },
974       { 0,              0,              0,      0 }
975     };
976     int i = mdwopt(argc, argv, "+a:b:B:p:e:c:t:R:C:A:s:n:lqrLKS",
977                    opt, 0, 0, 0);
978     if (i < 0)
979       break;
980
981     /* --- Handle the various options --- */
982
983     switch (i) {
984
985       /* --- Read an algorithm name --- */
986
987       case 'a': {
988         keyalg *a;
989         size_t sz = strlen(optarg);
990
991         if (strcmp(optarg, "list") == 0) {
992           for (a = algtab; a->name; a++)
993             printf("%-10s %s\n", a->name, a->help);
994           return (0);
995         }
996
997         alg = 0;
998         for (a = algtab; a->name; a++) {
999           if (strncmp(optarg, a->name, sz) == 0) {
1000             if (a->name[sz] == 0) {
1001               alg = a;
1002               break;
1003             } else if (alg)
1004               die(EXIT_FAILURE, "ambiguous algorithm name `%s'", optarg);
1005             else
1006               alg = a;
1007           }
1008         }
1009         if (!alg)
1010           die(EXIT_FAILURE, "unknown algorithm name `%s'", optarg);
1011       } break;
1012
1013       /* --- Bits must be nonzero and a multiple of 8 --- */
1014
1015       case 'b': {
1016         char *p;
1017         k.bits = strtoul(optarg, &p, 0);
1018         if (k.bits == 0 || *p != 0)
1019           die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1020       } break;
1021
1022       case 'B': {
1023         char *p;
1024         k.qbits = strtoul(optarg, &p, 0);
1025         if (k.qbits == 0 || *p != 0)
1026           die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1027       } break;
1028
1029       /* --- Parameter selection --- */
1030
1031       case 'p':
1032         ptag = optarg;
1033         break;
1034
1035       /* --- Expiry dates get passed to @get_date@ for parsing --- */
1036
1037       case 'e':
1038         if (strcmp(optarg, "forever") == 0)
1039           exp = KEXP_FOREVER;
1040         else {
1041           exp = get_date(optarg, 0);
1042           if (exp == -1)
1043             die(EXIT_FAILURE, "bad expiry date `%s'", optarg);
1044         }
1045         break;
1046
1047       /* --- Store comments without interpretation --- */
1048
1049       case 'c':
1050         if (key_chkcomment(optarg))
1051           die(EXIT_FAILURE, "bad comment string `%s'", optarg);
1052         c = optarg;
1053         break;
1054
1055       /* --- Elliptic curve parameters --- */
1056
1057       case 'C':
1058         k.curve = optarg;
1059         break;
1060
1061       /* --- Store tags --- */
1062
1063       case 't':
1064         if (key_chkident(optarg))
1065           die(EXIT_FAILURE, "bad tag string `%s'", optarg);
1066         tag = optarg;
1067         break;
1068       case 'r':
1069         k.f |= f_retag;
1070         break;
1071
1072       /* --- Seeding --- */
1073
1074       case 'A': {
1075         const struct seedalg *ss;
1076         if (strcmp(optarg, "list") == 0) {
1077           printf("Seed algorithms:\n");
1078           for (ss = seedtab; ss->p; ss++)
1079             printf("  %s\n", ss->p);
1080           exit(0);
1081         }
1082         if (seed) die(EXIT_FAILURE, "seed already set -- put -A first");
1083         sa = 0;
1084         for (ss = seedtab; ss->p; ss++) {
1085           if (strcmp(optarg, ss->p) == 0)
1086             sa = ss;
1087         }
1088         if (!sa)
1089           die(EXIT_FAILURE, "seed algorithm `%s' not known", optarg);
1090       } break;
1091
1092       case 's': {
1093         base64_ctx b;
1094         dstr d = DSTR_INIT;
1095         if (seed) die(EXIT_FAILURE, "seed already set"); 
1096         base64_init(&b);
1097         base64_decode(&b, optarg, strlen(optarg), &d);
1098         base64_decode(&b, 0, 0, &d);
1099         k.r = sa->gen(d.buf, d.len);
1100         seed = optarg;
1101         dstr_destroy(&d);
1102       } break;
1103         
1104       case 'n': {
1105         base64_ctx b;
1106         dstr d = DSTR_INIT;
1107         char *p;
1108         unsigned n = strtoul(optarg, &p, 0);
1109         if (n == 0 || *p != 0 || n % 8 != 0)
1110           die(EXIT_FAILURE, "bad seed length `%s'", optarg);
1111         if (seed) die(EXIT_FAILURE, "seed already set"); 
1112         n /= 8;
1113         p = xmalloc(n);
1114         rand_get(RAND_GLOBAL, p, n);
1115         base64_init(&b);
1116         base64_encode(&b, p, n, &d);
1117         base64_encode(&b, 0, 0, &d);
1118         seed = d.buf;
1119         k.r = sa->gen(p, n);
1120       } break;
1121         
1122       /* --- Other flags --- */
1123
1124       case 'R':
1125         rtag = optarg;
1126         break;
1127       case 'l':
1128         k.f |= f_lock;
1129         break;
1130       case 'q':
1131         k.f |= f_quiet;
1132         break;
1133       case 'L':
1134         k.f |= f_limlee;
1135         break;
1136       case 'K':
1137         k.f |= f_kcdsa;
1138         break;
1139       case 'S':
1140         k.f |= f_subgroup;
1141         break;
1142
1143       /* --- Other things are bogus --- */
1144
1145       default:
1146         k.f |= f_bogus;
1147         break;
1148     }
1149   }
1150
1151   /* --- Various sorts of bogosity --- */
1152
1153   if ((k.f & f_bogus) || optind + 1 > argc) {
1154     die(EXIT_FAILURE,
1155         "Usage: add [OPTIONS] TYPE [ATTR...]");
1156   }
1157   if (key_chkident(argv[optind]))
1158     die(EXIT_FAILURE, "bad key type `%s'", argv[optind]);
1159
1160   /* --- Set up various bits of the state --- */
1161
1162   if (exp == KEXP_EXPIRE)
1163     exp = time(0) + 14 * 24 * 60 * 60;
1164
1165   /* --- Open the file and create the basic key block --- *
1166    *
1167    * Keep on generating keyids until one of them doesn't collide.
1168    */
1169
1170   doopen(&f, KOPEN_WRITE);
1171   k.kf = &f;
1172
1173   /* --- Key the generator --- */
1174
1175   keyrand(&f, rtag);
1176
1177   for (;;) {
1178     uint32 id = rand_global.ops->word(&rand_global);
1179     int err;
1180     if ((err = key_new(&f, id, argv[optind], exp, &k.k)) == 0)
1181       break;
1182     else if (err != KERR_DUPID)
1183       die(EXIT_FAILURE, "error adding new key: %s", key_strerror(err));
1184   }
1185
1186   /* --- Set various simple attributes --- */
1187
1188   if (tag) {
1189     int err;
1190     key *kk;
1191     if (k.f & f_retag) {
1192       if ((kk = key_bytag(&f, tag)) != 0 &&
1193           kk->tag &&
1194           strcmp(kk->tag, tag) == 0)
1195         key_settag(&f, kk, 0);
1196     }
1197     if ((err = key_settag(&f, k.k, tag)) != 0)
1198       die(EXIT_FAILURE, "error setting key tag: %s", key_strerror(err));
1199   }
1200
1201   if (c) {
1202     int err = key_setcomment(&f, k.k, c);
1203     if (err)
1204       die(EXIT_FAILURE, "error setting key comment: %s", key_strerror(err));
1205   }
1206
1207   setattr(&f, k.k, argv + optind + 1);
1208   if (seed) {
1209     key_putattr(&f, k.k, "genseed", seed);
1210     key_putattr(&f, k.k, "seedalg", sa->p);
1211   }
1212
1213   key_fulltag(k.k, &k.tag);
1214
1215   /* --- Find the parameter key --- */
1216
1217   if (ptag) {
1218     if ((k.p = key_bytag(&f, ptag)) == 0)
1219       die(EXIT_FAILURE, "parameter key `%s' not found", ptag);
1220     if ((k.p->k->e & KF_ENCMASK) != KENC_STRUCT)
1221       die(EXIT_FAILURE, "parameter key `%s' is not structured", ptag);
1222   }
1223
1224   /* --- Now generate the actual key data --- */
1225
1226   alg->proc(&k);
1227
1228   /* --- Done --- */
1229
1230   dstr_destroy(&k.tag);
1231   doclose(&f);
1232   return (0);
1233 }
1234
1235 /*----- Key listing -------------------------------------------------------*/
1236
1237 /* --- Listing options --- */
1238
1239 typedef struct listopts {
1240   const char *tfmt;                     /* Date format (@strftime@-style) */
1241   int v;                                /* Verbosity level */
1242   unsigned f;                           /* Various flags */
1243   time_t t;                             /* Time now (for key expiry) */
1244   key_filter kf;                        /* Filter for matching keys */
1245 } listopts;
1246
1247 /* --- Listing flags --- */
1248
1249 #define f_newline 2u                    /* Write newline before next entry */
1250 #define f_attr 4u                       /* Written at least one attribute */
1251 #define f_utc 8u                        /* Emit UTC time, not local time */
1252
1253 /* --- @showkeydata@ --- *
1254  *
1255  * Arguments:   @key_data *k@ = pointer to key to write
1256  *              @int ind@ = indentation level
1257  *              @listopts *o@ = listing options
1258  *              @dstr *d@ = tag string for this subkey
1259  *
1260  * Returns:     ---
1261  *
1262  * Use:         Emits a piece of key data in a human-readable format.
1263  */
1264
1265 static void showkeydata(key_data *k, int ind, listopts *o, dstr *d)
1266 {
1267 #define INDENT(i) do {                                                  \
1268   int _i;                                                               \
1269   for (_i = 0; _i < (i); _i++) {                                        \
1270     putchar(' ');                                                       \
1271   }                                                                     \
1272 } while (0)
1273
1274   switch (k->e & KF_ENCMASK) {
1275
1276     /* --- Binary key data --- *
1277      *
1278      * Emit as a simple hex dump.
1279      */
1280
1281     case KENC_BINARY: {
1282       const octet *p = k->u.k.k;
1283       const octet *l = p + k->u.k.sz;
1284       size_t sz = 0;
1285
1286       fputs(" {", stdout);
1287       while (p < l) {
1288         if (sz % 16 == 0) {
1289           putchar('\n');
1290           INDENT(ind + 2);
1291         } else if (sz % 8 == 0)
1292           fputs("  ", stdout);
1293         else
1294           putc(' ', stdout);
1295         printf("%02x", *p++);
1296         sz++;
1297       }
1298       putchar('\n');
1299       INDENT(ind);
1300       fputs("}\n", stdout);
1301     } break;
1302
1303     /* --- Encrypted data --- *
1304      *
1305      * If the user is sufficiently keen, ask for a passphrase and decrypt the
1306      * key.  Otherwise just say that it's encrypted and move on.
1307      */
1308
1309     case KENC_ENCRYPT:
1310       if (o->v <= 3)
1311         fputs(" encrypted\n", stdout);
1312       else {
1313         key_data *kd;
1314         if (key_punlock(&kd, k, d->buf))
1315           printf(" <failed to unlock %s>\n", d->buf);
1316         else {
1317           fputs(" encrypted", stdout);
1318           showkeydata(kd, ind, o, d);
1319           key_drop(kd);
1320         }
1321       }
1322       break;
1323
1324     /* --- Integer keys --- *
1325      *
1326      * Emit as a large integer in decimal.  This makes using the key in
1327      * `calc' or whatever easier.
1328      */
1329
1330     case KENC_MP:
1331       putchar(' ');
1332       mp_writefile(k->u.m, stdout, 10);
1333       putchar('\n');
1334       break;
1335
1336     /* --- Strings --- */
1337
1338     case KENC_STRING:
1339       printf(" `%s'\n", k->u.p);
1340       break;
1341
1342     /* --- Elliptic curve points --- */
1343
1344     case KENC_EC:
1345       if (EC_ATINF(&k->u.e))
1346         fputs(" inf\n", stdout);
1347       else {
1348         fputs(" 0x", stdout); mp_writefile(k->u.e.x, stdout, 16);
1349         fputs(", 0x", stdout); mp_writefile(k->u.e.y, stdout, 16);
1350         putchar('\n');
1351       }
1352       break;      
1353
1354     /* --- Structured keys --- *
1355      *
1356      * Just iterate over the subkeys.
1357      */
1358
1359     case KENC_STRUCT: {
1360       key_subkeyiter i;
1361       const char *tag;
1362       size_t n = d->len;
1363
1364       fputs(" {\n", stdout);
1365       for (key_mksubkeyiter(&i, k); key_nextsubkey(&i, &tag, &k); ) {
1366         if (!key_match(k, &o->kf))
1367           continue;
1368         INDENT(ind + 2);
1369         printf("%s =", tag);
1370         d->len = n;
1371         dstr_putf(d, ".%s", tag);
1372         showkeydata(k, ind + 2, o, d);
1373       }
1374       INDENT(ind);
1375       fputs("}\n", stdout);
1376     } break;      
1377   }
1378
1379 #undef INDENT
1380 }
1381
1382 /* --- @showkey@ --- *
1383  *
1384  * Arguments:   @key *k@ = pointer to key to show
1385  *              @listopts *o@ = pointer to listing options
1386  *
1387  * Returns:     ---
1388  *
1389  * Use:         Emits a listing of a particular key.
1390  */
1391
1392 static void showkey(key *k, listopts *o)
1393 {
1394   char ebuf[24], dbuf[24];
1395   struct tm *tm;
1396
1397   /* --- Skip the key if the filter doesn't match --- */
1398
1399   if (!key_match(k->k, &o->kf))
1400     return;
1401
1402   /* --- Sort out the expiry and deletion times --- */
1403
1404   if (KEY_EXPIRED(o->t, k->exp))
1405     strcpy(ebuf, "expired");
1406   else if (k->exp == KEXP_FOREVER)
1407     strcpy(ebuf, "forever");
1408   else {
1409     tm = (o->f & f_utc) ? gmtime(&k->exp) : localtime(&k->exp);
1410     strftime(ebuf, sizeof(ebuf), o->tfmt, tm);
1411   }
1412
1413   if (KEY_EXPIRED(o->t, k->del))
1414     strcpy(dbuf, "deleted");
1415   else if (k->del == KEXP_FOREVER)
1416     strcpy(dbuf, "forever");
1417   else {
1418     tm = (o->f & f_utc) ? gmtime(&k->del) : localtime(&k->del);
1419     strftime(dbuf, sizeof(dbuf), o->tfmt, tm);
1420   }
1421
1422   /* --- If in compact format, just display and quit --- */
1423
1424   if (!o->v) {
1425     if (!(o->f & f_newline)) {
1426       printf("%8s  %-20s  %-20s  %-10s  %-10s\n",
1427              "Id", "Tag", "Type", "Expire", "Delete");
1428     }
1429     printf("%08lx  %-20s  %-20s  %-10s  %-10s\n",
1430            (unsigned long)k->id, k->tag ? k->tag : "<none>",
1431            k->type, ebuf, dbuf);
1432     o->f |= f_newline;
1433     return;
1434   }
1435
1436   /* --- Display the standard header --- */
1437
1438   if (o->f & f_newline)
1439     fputc('\n', stdout);
1440   printf("keyid: %08lx\n", (unsigned long)k->id);
1441   printf("tag: %s\n", k->tag ? k->tag : "<none>");
1442   printf("type: %s\n", k->type);
1443   printf("expiry: %s\n", ebuf);
1444   printf("delete: %s\n", dbuf);
1445   printf("comment: %s\n", k->c ? k->c : "<none>");
1446
1447   /* --- Display the attributes --- */
1448
1449   if (o->v > 1) {
1450     key_attriter i;
1451     const char *av, *an;
1452
1453     o->f &= ~f_attr;
1454     printf("attributes:");
1455     for (key_mkattriter(&i, k); key_nextattr(&i, &an, &av); ) {
1456       printf("\n  %s = %s", an, av);
1457       o->f |= f_attr;
1458     }
1459     if (o->f & f_attr)
1460       fputc('\n', stdout);
1461     else
1462       puts(" <none>");
1463   }
1464
1465   /* --- If dumping requested, dump the raw key data --- */
1466
1467   if (o->v > 2) {
1468     dstr d = DSTR_INIT;
1469     fputs("key:", stdout);
1470     key_fulltag(k, &d);
1471     showkeydata(k->k, 0, o, &d);
1472     dstr_destroy(&d);
1473   }
1474     
1475   o->f |= f_newline;
1476 }
1477
1478 /* --- @cmd_list@ --- */
1479
1480 static int cmd_list(int argc, char *argv[])
1481 {
1482   key_file f;
1483   key *k;
1484   listopts o = { 0, 0, 0, 0, { 0, 0 } };
1485
1486   /* --- Parse subcommand options --- */
1487
1488   for (;;) {
1489     static struct option opt[] = {
1490       { "quiet",        0,              0,      'q' },
1491       { "verbose",      0,              0,      'v' },
1492       { "utc",          0,              0,      'u' },
1493       { "filter",       OPTF_ARGREQ,    0,      'f' },
1494       { 0,              0,              0,      0 }
1495     };
1496     int i = mdwopt(argc, argv, "+uqvf:", opt, 0, 0, 0);
1497     if (i < 0)
1498       break;
1499
1500     switch (i) {
1501       case 'u':
1502         o.f |= f_utc;
1503         break;
1504       case 'q':
1505         if (o.v)
1506           o.v--;
1507         break;
1508       case 'v':
1509         o.v++;
1510         break;
1511       case 'f': {
1512         char *p;
1513         int e = key_readflags(optarg, &p, &o.kf.f, &o.kf.m);
1514         if (e || *p)
1515           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1516       } break;  
1517       default:
1518         o.f |= f_bogus;
1519         break;
1520     }
1521   }
1522
1523   if (o.f & f_bogus)
1524     die(EXIT_FAILURE, "Usage: list [-uqv] [-f FILTER] [TAG...]");
1525
1526   /* --- Open the key file --- */
1527
1528   doopen(&f, KOPEN_READ);
1529   o.t = time(0);
1530
1531   /* --- Set up the time format --- */
1532
1533   if (!o.v)
1534     o.tfmt = "%Y-%m-%d";
1535   else if (o.f & f_utc)
1536     o.tfmt = "%Y-%m-%d %H:%M:%S UTC";
1537   else
1538     o.tfmt = "%Y-%m-%d %H:%M:%S %Z";
1539
1540   /* --- If specific keys were requested use them, otherwise do all --- *
1541    *
1542    * Some day, this might turn into a wildcard match.
1543    */
1544
1545   if (optind < argc) {
1546     do {
1547       if ((k = key_bytag(&f, argv[optind])) != 0)
1548         showkey(k, &o);
1549       else {
1550         moan("key `%s' not found", argv[optind]);
1551         o.f |= f_bogus;
1552       }
1553       optind++;
1554     } while (optind < argc);
1555   } else {
1556     key_iter i;
1557     for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1558       showkey(k, &o);
1559   }
1560
1561   /* --- Done --- */
1562
1563   doclose(&f);
1564   if (o.f & f_bogus)
1565     return (EXIT_FAILURE);
1566   else
1567     return (0);
1568 }
1569
1570 /*----- Command implementation --------------------------------------------*/
1571
1572 /* --- @cmd_expire@ --- */
1573
1574 static int cmd_expire(int argc, char *argv[])
1575 {
1576   key_file f;
1577   key *k;
1578   int i;
1579   int rc = 0;
1580
1581   if (argc < 2)
1582     die(EXIT_FAILURE, "Usage: expire TAG...");
1583   doopen(&f, KOPEN_WRITE);
1584   for (i = 1; i < argc; i++) {
1585     if ((k = key_bytag(&f, argv[i])) != 0)
1586       key_expire(&f, k);
1587     else {
1588       moan("key `%s' not found", argv[i]);
1589       rc = 1;
1590     }
1591   }
1592   doclose(&f);
1593   return (rc);
1594 }
1595
1596 /* --- @cmd_delete@ --- */
1597
1598 static int cmd_delete(int argc, char *argv[])
1599 {
1600   key_file f;
1601   key *k;
1602   int i;
1603   int rc = 0;
1604
1605   if (argc < 2)
1606     die(EXIT_FAILURE, "Usage: delete TAG...");
1607   doopen(&f, KOPEN_WRITE);
1608   for (i = 1; i < argc; i++) {
1609     if ((k = key_bytag(&f, argv[i])) != 0)
1610       key_delete(&f, k);
1611     else {
1612       moan("key `%s' not found", argv[i]);
1613       rc = 1;
1614     }
1615   }
1616   doclose(&f);
1617   return (rc);
1618 }
1619
1620 /* --- @cmd_setattr@ --- */
1621
1622 static int cmd_setattr(int argc, char *argv[])
1623 {
1624   key_file f;
1625   key *k;
1626
1627   if (argc < 3)
1628     die(EXIT_FAILURE, "Usage: setattr TAG ATTR...");
1629   doopen(&f, KOPEN_WRITE);
1630   if ((k = key_bytag(&f, argv[1])) == 0)
1631     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1632   setattr(&f, k, argv + 2);
1633   doclose(&f);
1634   return (0);
1635 }
1636
1637 /* --- @cmd_getattr@ --- */
1638
1639 static int cmd_getattr(int argc, char *argv[])
1640 {
1641   key_file f;
1642   key *k;
1643   dstr d = DSTR_INIT;
1644   const char *p;
1645
1646   if (argc != 3)
1647     die(EXIT_FAILURE, "Usage: getattr TAG ATTR");
1648   doopen(&f, KOPEN_READ);
1649   if ((k = key_bytag(&f, argv[1])) == 0)
1650     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1651   key_fulltag(k, &d);
1652   if ((p = key_getattr(&f, k, argv[2])) == 0)
1653     die(EXIT_FAILURE, "no attribute `%s' for key `%s'", argv[2], d.buf);
1654   puts(p);
1655   dstr_destroy(&d);
1656   doclose(&f);
1657   return (0);
1658 }
1659
1660 /* --- @cmd_finger@ --- */
1661
1662 static void fingerprint(key *k, const gchash *ch, const key_filter *kf)
1663 {
1664   ghash *h;
1665   dstr d = DSTR_INIT;
1666   const octet *p;
1667   size_t i;
1668
1669   h = GH_INIT(ch);
1670   if (key_fingerprint(k, h, kf)) {
1671     p = GH_DONE(h, 0);
1672     key_fulltag(k, &d);
1673     for (i = 0; i < ch->hashsz; i++) {
1674       if (i && i % 4 == 0)
1675         putchar('-');
1676       printf("%02x", p[i]);
1677     }
1678     printf(" %s\n", d.buf);
1679   }
1680   dstr_destroy(&d);
1681   GH_DESTROY(h);
1682 }
1683
1684 static int cmd_finger(int argc, char *argv[])
1685 {
1686   key_file f;
1687   int rc = 0;
1688   const gchash *ch = &rmd160;
1689   key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1690
1691   for (;;) {
1692     static struct option opt[] = {
1693       { "filter",       OPTF_ARGREQ,    0,      'f' },
1694       { "algorithm",    OPTF_ARGREQ,    0,      'a' },
1695       { 0,              0,              0,      0 }
1696     };
1697     int i = mdwopt(argc, argv, "+f:a:", opt, 0, 0, 0);
1698     if (i < 0)
1699       break;
1700     switch (i) {
1701       case 'f': {
1702         char *p;
1703         int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1704         if (err || *p)
1705           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1706       } break;
1707       case 'a':
1708         if ((ch = ghash_byname(optarg)) == 0)
1709           die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1710         break;
1711       default:
1712         rc = 1;
1713         break;
1714     }
1715   }
1716
1717   argv += optind; argc -= optind;
1718   if (rc)
1719     die(EXIT_FAILURE, "Usage: fingerprint [-f FILTER] [TAG...]");
1720
1721   doopen(&f, KOPEN_READ);
1722
1723   if (argc) {
1724     int i;
1725     for (i = 0; i < argc; i++) {
1726       key *k = key_bytag(&f, argv[i]);
1727       if (k)
1728         fingerprint(k, ch, &kf);
1729       else {
1730         rc = 1;
1731         moan("key `%s' not found", argv[i]);
1732       }
1733     }
1734   } else {
1735     key_iter i;
1736     key *k;
1737     for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1738       fingerprint(k, ch, &kf);
1739   }
1740   return (rc);
1741 }
1742
1743 /* --- @cmd_verify@ --- */
1744
1745 static unsigned xdigit(char c)
1746 {
1747   if ('A' <= c && c <= 'Z') return (c + 10 - 'A');
1748   if ('a' <= c && c <= 'z') return (c + 10 - 'a');
1749   if ('0' <= c && c <= '9') return (c - '0');
1750   return (~0u);
1751 }
1752
1753 static void unhexify(octet *q, char *p, size_t n)
1754 {
1755   unsigned a = 0;
1756   int i = 0;
1757
1758   for (;;) {
1759     if (*p == '-' || *p == ':' || isspace((unsigned char)*p)) {
1760       p++;
1761       continue;
1762     }
1763     if (!n && !*p)
1764       break;
1765     if (!*p)
1766       die(EXIT_FAILURE, "hex string too short");
1767     if (!isxdigit((unsigned char)*p))
1768       die(EXIT_FAILURE, "bad hex string");
1769     if (!n)
1770       die(EXIT_FAILURE, "hex string too long");
1771     a = (a << 4) | xdigit(*p++);
1772     i++;
1773     if (i == 2) {
1774       *q++ = U8(a);
1775       a = 0;
1776       i = 0;
1777       n--;
1778     }
1779   }
1780 }
1781
1782 static int cmd_verify(int argc, char *argv[])
1783 {
1784   key_file f;
1785   int rc = 0;
1786   const gchash *ch = &rmd160;
1787   ghash *h;
1788   key *k;
1789   octet *buf;
1790   const octet *fpr;
1791   key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1792
1793   for (;;) {
1794     static struct option opt[] = {
1795       { "filter",       OPTF_ARGREQ,    0,      'f' },
1796       { "algorithm",    OPTF_ARGREQ,    0,      'a' },
1797       { 0,              0,              0,      0 }
1798     };
1799     int i = mdwopt(argc, argv, "+f:a:", opt, 0, 0, 0);
1800     if (i < 0)
1801       break;
1802     switch (i) {
1803       case 'f': {
1804         char *p;
1805         int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1806         if (err || *p)
1807           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1808       } break;
1809       case 'a':
1810         if ((ch = ghash_byname(optarg)) == 0)
1811           die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1812         break;
1813       default:
1814         rc = 1;
1815         break;
1816     }
1817   }
1818
1819   argv += optind; argc -= optind;
1820   if (rc || argc != 2)
1821     die(EXIT_FAILURE, "Usage: verify [-f FILTER] TAG FINGERPRINT");
1822
1823   doopen(&f, KOPEN_READ);
1824
1825   if ((k = key_bytag(&f, argv[0])) == 0)
1826     die(EXIT_FAILURE, "key `%s' not found", argv[0]);
1827   buf = xmalloc(ch->hashsz);
1828   unhexify(buf, argv[1], ch->hashsz);
1829   h = GH_INIT(ch);
1830   if (!key_fingerprint(k, h, &kf))
1831     die(EXIT_FAILURE, "key has no fingerprintable components (as filtered)");
1832   fpr = GH_DONE(h, 0);
1833   if (memcmp(fpr, buf, ch->hashsz) != 0)
1834     die(EXIT_FAILURE, "key fingerprint mismatch");
1835   doclose(&f);
1836   return (0);
1837 }
1838   
1839 /* --- @cmd_comment@ --- */
1840
1841 static int cmd_comment(int argc, char *argv[])
1842 {
1843   key_file f;
1844   key *k;
1845   int err;
1846
1847   if (argc < 2 || argc > 3)
1848     die(EXIT_FAILURE, "Usage: comment TAG [COMMENT]");
1849   doopen(&f, KOPEN_WRITE);
1850   if ((k = key_bytag(&f, argv[1])) == 0)
1851     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1852   if ((err = key_setcomment(&f, k, argv[2])) != 0)
1853     die(EXIT_FAILURE, "bad comment `%s': %s", argv[2], key_strerror(err));
1854   doclose(&f);
1855   return (0);
1856 }
1857
1858 /* --- @cmd_tag@ --- */
1859
1860 static int cmd_tag(int argc, char *argv[])
1861 {
1862   key_file f;
1863   key *k;
1864   int err;
1865   unsigned flags = 0;
1866   int rc = 0;
1867
1868   for (;;) {
1869     static struct option opt[] = {
1870       { "retag",        0,              0,      'r' },
1871       { 0,              0,              0,      0 }
1872     };
1873     int i = mdwopt(argc, argv, "+r", opt, 0, 0, 0);
1874     if (i < 0)
1875       break;
1876     switch (i) {
1877       case 'r':
1878         flags |= f_retag;
1879         break;
1880       default:
1881         rc = 1;
1882         break;
1883     }
1884   }
1885
1886   argv += optind; argc -= optind;
1887   if (argc < 1 || argc > 2 || rc)
1888     die(EXIT_FAILURE, "Usage: tag [-r] TAG [NEW-TAG]");
1889   doopen(&f, KOPEN_WRITE);
1890   if (flags & f_retag) {
1891     if ((k = key_bytag(&f, argv[1])) != 0 && strcmp(k->tag, argv[1]) == 0)
1892       key_settag(&f, k, 0);
1893   }
1894   if ((k = key_bytag(&f, argv[0])) == 0)
1895     die(EXIT_FAILURE, "key `%s' not found", argv[0]);
1896   if ((err = key_settag(&f, k, argv[1])) != 0)
1897     die(EXIT_FAILURE, "bad tag `%s': %s", argv[1], key_strerror(err));
1898   doclose(&f);
1899   return (0);
1900 }
1901
1902 /* --- @cmd_lock@ --- */
1903
1904 static int cmd_lock(int argc, char *argv[])
1905 {
1906   key_file f;
1907   key *k;
1908   key_data **kd;
1909   dstr d = DSTR_INIT;
1910
1911   if (argc != 2)
1912     die(EXIT_FAILURE, "Usage: lock QTAG");
1913   doopen(&f, KOPEN_WRITE);
1914   if (key_qtag(&f, argv[1], &d, &k, &kd))
1915     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1916   if ((*kd)->e == KENC_ENCRYPT && key_punlock(kd, 0, d.buf))
1917     die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
1918   if (key_plock(kd, 0, d.buf))
1919     die(EXIT_FAILURE, "failed to lock key `%s'", d.buf);
1920   f.f |= KF_MODIFIED;
1921   doclose(&f);
1922   return (0);
1923 }
1924
1925 /* --- @cmd_unlock@ --- */
1926
1927 static int cmd_unlock(int argc, char *argv[])
1928 {
1929   key_file f;
1930   key *k;
1931   key_data **kd;
1932   dstr d = DSTR_INIT;
1933
1934   if (argc != 2)
1935     die(EXIT_FAILURE, "Usage: unlock QTAG");
1936   doopen(&f, KOPEN_WRITE);
1937   if (key_qtag(&f, argv[1], &d, &k, &kd))
1938     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1939   if ((*kd)->e != KENC_ENCRYPT)
1940     die(EXIT_FAILURE, "key `%s' is not encrypted", d.buf);
1941   if (key_punlock(kd, 0, d.buf))
1942     die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
1943   f.f |= KF_MODIFIED;
1944   doclose(&f);
1945   return (0);
1946 }
1947
1948 /* --- @cmd_extract@ --- */
1949
1950 static int cmd_extract(int argc, char *argv[])
1951 {
1952   key_file f;
1953   key *k;
1954   int i;
1955   int rc = 0;
1956   key_filter kf = { 0, 0 };
1957   dstr d = DSTR_INIT;
1958   const char *outfile = 0;
1959   FILE *fp;
1960
1961   for (;;) {
1962     static struct option opt[] = {
1963       { "filter",       OPTF_ARGREQ,    0,      'f' },
1964       { 0,              0,              0,      0 }
1965     };
1966     int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
1967     if (i < 0)
1968       break;
1969     switch (i) {
1970       case 'f': {
1971         char *p;
1972         int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1973         if (err || *p)
1974           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1975       } break;
1976       default:
1977         rc = 1;
1978         break;
1979     }
1980   }
1981
1982   argv += optind; argc -= optind;
1983   if (rc || argc < 1)
1984     die(EXIT_FAILURE, "Usage: extract [-f FILTER] FILE [TAG...]");
1985   if (strcmp(*argv, "-") == 0)
1986     fp = stdout;
1987   else {
1988     outfile = *argv;
1989     dstr_putf(&d, "%s.new", outfile);
1990     if (!(fp = fopen(d.buf, "w"))) {
1991       die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
1992           d.buf, strerror(errno));
1993     }
1994   }
1995
1996   doopen(&f, KOPEN_READ);
1997   if (argc < 2) {
1998     key_iter i;
1999     key *k;
2000     for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
2001       key_extract(&f, k, fp, &kf);
2002   } else {    
2003     for (i = 1; i < argc; i++) {
2004       if ((k = key_bytag(&f, argv[i])) != 0)
2005         key_extract(&f, k, fp, &kf);
2006       else {
2007         moan("key `%s' not found", argv[i]);
2008         rc = 1;
2009       }
2010     }
2011   }
2012   if (fclose(fp) || (outfile && rename(d.buf, outfile)))
2013     die(EXIT_FAILURE, "error writing file: %s", strerror(errno));
2014   dstr_destroy(&d);
2015   doclose(&f);
2016   return (rc);
2017 }
2018
2019 /* --- @cmd_tidy@ --- */
2020
2021 static int cmd_tidy(int argc, char *argv[])
2022 {
2023   key_file f;
2024   if (argc != 1)
2025     die(EXIT_FAILURE, "Usage: tidy");
2026   doopen(&f, KOPEN_WRITE);
2027   f.f |= KF_MODIFIED; /* Nasty hack */
2028   doclose(&f);
2029   return (0);
2030 }
2031
2032 /* --- @cmd_merge@ --- */
2033
2034 static int cmd_merge(int argc, char *argv[])
2035 {
2036   key_file f;
2037   FILE *fp;
2038
2039   if (argc != 2)
2040     die(EXIT_FAILURE, "Usage: merge FILE");
2041   if (strcmp(argv[1], "-") == 0)
2042     fp = stdin;
2043   else if (!(fp = fopen(argv[1], "r"))) {
2044     die(EXIT_FAILURE, "couldn't open `%s' for reading: %s",
2045         argv[1], strerror(errno));
2046   }
2047
2048   doopen(&f, KOPEN_WRITE);
2049   key_merge(&f, argv[1], fp, key_moan, 0);
2050   doclose(&f);
2051   return (0);
2052 }
2053
2054 /* --- @cmd_show@ --- */
2055
2056 #define LISTS(LI)                                                       \
2057   LI("Lists", list,                                                     \
2058      listtab[i].name, listtab[i].name)                                  \
2059   LI("Hash functions", hash,                                            \
2060      ghashtab[i], ghashtab[i]->name)                                    \
2061   LI("Elliptic curves", ec,                                             \
2062      ectab[i].name, ectab[i].name)                                      \
2063   LI("Prime Diffie-Hellman groups", dh,                                 \
2064      ptab[i].name, ptab[i].name)                                        \
2065   LI("Binary Diffie-Hellman groups", bindh,                             \
2066      bintab[i].name, bintab[i].name)                                    \
2067   LI("Key-generation algorithms", keygen,                               \
2068      algtab[i].name, algtab[i].name)                                    \
2069   LI("Random seeding algorithms", seed,                                 \
2070      seedtab[i].p, seedtab[i].p)
2071
2072 MAKELISTTAB(listtab, LISTS)
2073
2074 static int cmd_show(int argc, char *argv[])
2075 {
2076   return (displaylists(listtab, argv + 1));
2077 }
2078
2079 /*----- Main command table ------------------------------------------------*/
2080
2081 static int cmd_help(int argc, char *argv[]);
2082
2083 static cmd cmds[] = {
2084   { "help", cmd_help, "help [COMMAND...]" },
2085   { "show", cmd_show, "show [ITEM...]" },
2086   { "list", cmd_list, "list [-uqv] [-f FILTER] [TAG...]", "\
2087 Options:\n\
2088 \n\
2089 -u, --utc               Display expiry times etc. in UTC, not local time.\n\
2090 -q, --quiet             Show less information.\n\
2091 -v, --verbose           Show more information.\n\
2092 " },
2093   { "fingerprint", cmd_finger, "fingerprint [-f FILTER] [TAG...]", "\
2094 Options:\n\
2095 \n\
2096 -f, --filter=FILT       Only hash key components matching FILT.\n\
2097 -a, --algorithm=HASH    Use the named HASH algorithm.\n\
2098                           ($ show hash for list.)\n\
2099 " },
2100   { "verify", cmd_verify, "verify [-f FILTER] TAG FINGERPRINT", "\
2101 Options:\n\
2102 \n\
2103 -f, --filter=FILT       Only hash key components matching FILT.\n\
2104 -a, --algorithm=HASH    Use the named HASH algorithm.\n\
2105                           ($ show hash for list.)\n\
2106 " },
2107   { "extract", cmd_extract, "extract [-f FILTER] FILE [TAG...]", "\
2108 Options:\n\
2109 \n\
2110 -f, --filter=FILT       Only extract key components matching FILT.\n\
2111 " },
2112   { "merge", cmd_merge, "merge FILE" },
2113   { "expire", cmd_expire, "expire TAG..." },
2114   { "delete", cmd_delete, "delete TAG..." },
2115   { "setattr", cmd_setattr, "setattr TAG ATTR..." },
2116   { "getattr", cmd_getattr, "getattr TAG ATTR" },
2117   { "comment", cmd_comment, "comment TAG [COMMENT]" },
2118   { "lock", cmd_lock, "lock QTAG" },
2119   { "unlock", cmd_unlock, "unlock QTAG" },
2120   { "tag", cmd_tag, "tag [-r] TAG [NEW-TAG]", "\
2121 Options:\n\
2122 \n\
2123 -r, --retag             Untag any key currently called new-tag.\n\
2124 " },
2125   { "tidy", cmd_tidy, "tidy" },
2126   { "add", cmd_add,
2127     "add [-OPTIONS] TYPE [ATTR...]\n\
2128         Options: [-lqrLKS] [-a ALG] [-bB BITS] [-p PARAM] [-R TAG]\n\
2129                  [-A SEEDALG] [-s SEED] [-n BITS]\n\
2130                  [-e EXPIRE] [-t TAG] [-c COMMENT]", "\
2131 Options:\n\
2132 \n\
2133 -a, --algorithm=ALG     Generate keys suitable for ALG.\n\
2134                           ($ show keygen for list.)\n\
2135 -b, --bits=N            Generate an N-bit key.\n\
2136 -B, --qbits=N           Use an N-bit subgroup or factors.\n\
2137 -p, --parameters=TAG    Get group parameters from TAG.\n\
2138 -C, --curve=NAME        Use elliptic curve or DH group NAME.\n\
2139                           ($ show ec or $ show dh for list.)\n\
2140 -A, --seedalg=ALG       Use pseudorandom generator ALG to generate key.\n\
2141                           ($ show seed for list.)\n\
2142 -s, --seed=BASE64       Use Base64-encoded string BASE64 as seed.\n\
2143 -n, --newseed=COUNT     Generate new COUNT-bit seed.\n\
2144 -e, --expire=TIME       Make the key expire after TIME.\n\
2145 -c, --comment=STRING    Attach the command STRING to the key.\n\
2146 -t, --tag=TAG           Tag the key with the name TAG.\n\
2147 -r, --retag             Untag any key currently with that tag.\n\
2148 -R, --rand-id=TAG       Use key named TAG for the random number generator.\n\
2149 -l, --lock              Lock the generated key with a passphrase.\n\
2150 -q, --quiet             Don't give progress indicators while working.\n\
2151 -L, --lim-lee           Generate Lim-Lee primes for Diffie-Hellman groups.\n\
2152 -K, --kcdsa             Generate KCDSA-style Lim-Lee primes for DH groups.\n\
2153 -S, --subgroup          Use a prime-order subgroup for Diffie-Hellman.\n\
2154 " },
2155   { 0, 0, 0 }
2156 };
2157
2158 static int cmd_help(int argc, char *argv[])
2159 {
2160   sc_help(cmds, stdout, argv + 1);
2161   return (0);
2162 }
2163
2164 /*----- Main code ---------------------------------------------------------*/
2165
2166 /* --- Helpful GNUy functions --- */
2167
2168 static void usage(FILE *fp)
2169 {
2170   pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
2171 }
2172
2173 void version(FILE *fp)
2174 {
2175   pquis(fp, "$, Catacomb version " VERSION "\n");
2176 }
2177
2178 void help_global(FILE *fp)
2179 {
2180   usage(fp);
2181   fputs("\n\
2182 Performs various simple key management operations.\n\
2183 \n\
2184 Global command line options:\n\
2185 \n\
2186 -h, --help [COMMAND...] Display this help text (or help for COMMANDs).\n\
2187 -v, --version           Display version number.\n\
2188 -u, --usage             Display short usage summary.\n\
2189 \n\
2190 -k, --keyring=FILE      Read and write keys in FILE.\n",
2191         fp);
2192 }
2193
2194 /* --- @main@ --- *
2195  *
2196  * Arguments:   @int argc@ = number of command line arguments
2197  *              @char *argv[]@ = array of command line arguments
2198  *
2199  * Returns:     Nonzero on failure.
2200  *
2201  * Use:         Main program.  Performs simple key management functions.
2202  */
2203
2204 int main(int argc, char *argv[])
2205 {
2206   unsigned f = 0;
2207
2208 #define f_bogus 1u
2209
2210   /* --- Initialization --- */
2211
2212   ego(argv[0]);
2213   sub_init();
2214
2215   /* --- Parse command line options --- */
2216
2217   for (;;) {
2218     static struct option opt[] = {
2219
2220       /* --- Standard GNUy help options --- */
2221
2222       { "help",         0,              0,      'h' },
2223       { "version",      0,              0,      'v' },
2224       { "usage",        0,              0,      'u' },
2225
2226       /* --- Real live useful options --- */
2227
2228       { "keyring",      OPTF_ARGREQ,    0,      'k' },
2229
2230       /* --- Magic terminator --- */
2231
2232       { 0,              0,              0,      0 }
2233     };
2234     int i = mdwopt(argc, argv, "+hvu k:", opt, 0, 0, 0);
2235
2236     if (i < 0)
2237       break;
2238     switch (i) {
2239
2240       /* --- GNU help options --- */
2241
2242       case 'h':
2243         sc_help(cmds, stdout, argv + optind);
2244         exit(0);
2245       case 'v':
2246         version(stdout);
2247         exit(0);
2248       case 'u':
2249         usage(stdout);
2250         exit(0);
2251
2252       /* --- Real useful options --- */
2253
2254       case 'k':
2255         keyfile = optarg;
2256         break;
2257
2258       /* --- Bogosity --- */
2259
2260       default:
2261         f |= f_bogus;
2262         break;
2263     }
2264   }
2265
2266   /* --- Complain about excessive bogons --- */
2267
2268   if (f & f_bogus || optind == argc) {
2269     usage(stderr);
2270     exit(1);
2271   }
2272
2273   /* --- Initialize the Catacomb random number generator --- */
2274
2275   rand_noisesrc(RAND_GLOBAL, &noise_source);
2276   rand_seed(RAND_GLOBAL, 160);
2277
2278   /* --- Dispatch to appropriate command handler --- */
2279
2280   argc -= optind;
2281   argv += optind;
2282   optind = 0;
2283   return (findcmd(cmds, argv[0])->cmd(argc, argv));
2284 }
2285
2286 /*----- That's all, folks -------------------------------------------------*/