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