chiark / gitweb /
math/fgoldi.[ch]: Implement the extra operations needed for Ed448.
[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 #define XDHS(_)                                                         \
949   _(x25519, X25519, "X25519")                                           \
950   _(x448, X448, "X448")
951
952 #define XDHALG(xdh, XDH, name)                                          \
953                                                                         \
954   static void alg_##xdh(keyopts *k)                                     \
955   {                                                                     \
956     key_data *kd, *kkd;                                                 \
957     octet priv[XDH##_KEYSZ], pub[XDH##_PUBSZ];                          \
958                                                                         \
959     copyparam(k, 0);                                                    \
960     k->r->ops->fill(k->r, priv, sizeof(priv));                          \
961     xdh(pub, priv, xdh##_base);                                         \
962     kkd = key_newstruct();                                              \
963     key_structsteal(kkd, "priv",                                        \
964                     key_newbinary(KCAT_PRIV | KF_BURN,                  \
965                                   priv, sizeof(priv)));                 \
966     kd = key_newstruct();                                               \
967     key_structsteal(kd, "private", kkd);                                \
968     key_structsteal(kd, "pub",                                          \
969                     key_newbinary(KCAT_PUB, pub, sizeof(pub)));         \
970                                                                         \
971     key_setkeydata(k->kf, k->k, kd);                                    \
972   }
973
974 XDHS(XDHALG)
975 #undef XDHALG
976
977 #define EDDSAS(_)                                                       \
978   _(ed25519, ED25519, "Ed25519")
979
980 #define EDDSAALG(ed, ED, name)                                          \
981                                                                         \
982   static void alg_##ed(keyopts *k)                                      \
983   {                                                                     \
984     key_data *kd, *kkd;                                                 \
985     octet priv[ED##_KEYSZ], pub[ED##_PUBSZ];                            \
986                                                                         \
987     copyparam(k, 0);                                                    \
988     k->r->ops->fill(k->r, priv, sizeof(priv));                          \
989     ed##_pubkey(pub, priv, sizeof(priv));                               \
990     kkd = key_newstruct();                                              \
991     key_structsteal(kkd, "priv",                                        \
992                     key_newbinary(KCAT_PRIV | KF_BURN,                  \
993                                   priv, sizeof(priv)));                 \
994     kd = key_newstruct();                                               \
995     key_structsteal(kd, "private", kkd);                                \
996     key_structsteal(kd, "pub",                                          \
997                     key_newbinary(KCAT_PUB, pub, sizeof(pub)));         \
998                                                                         \
999     key_setkeydata(k->kf, k->k, kd);                                    \
1000   }
1001
1002 EDDSAS(EDDSAALG)
1003 #undef EDDSAALG
1004
1005 /* --- The algorithm tables --- */
1006
1007 typedef struct keyalg {
1008   const char *name;
1009   void (*proc)(keyopts *o);
1010   const char *help;
1011 } keyalg;
1012
1013 static keyalg algtab[] = {
1014   { "binary",           alg_binary,     "Plain binary data" },
1015   { "des",              alg_des,        "Binary with DES-style parity" },
1016   { "rsa",              alg_rsa,        "RSA public-key encryption" },
1017   { "bbs",              alg_bbs,        "Blum-Blum-Shub generator" },
1018   { "dsa",              alg_dsa,        "DSA digital signatures" },
1019   { "dsa-param",        alg_dsaparam,   "DSA shared parameters" },
1020   { "dh",               alg_dh,         "Diffie-Hellman key exchange" },
1021   { "dh-param",         alg_dhparam,    "Diffie-Hellman parameters" },
1022   { "bindh",            alg_bin,        "DH over a binary field" },
1023   { "bindh-param",      alg_binparam,   "Binary-field DH parameters" },
1024   { "ec-param",         alg_ecparam,    "Elliptic curve parameters" },
1025   { "ec",               alg_ec,         "Elliptic curve crypto" },
1026 #define XDHTAB(xdh, XDH, name)                                          \
1027   { #xdh,               alg_##xdh,      "" name " key exchange" },
1028   XDHS(XDHTAB)
1029 #undef XDHTAB
1030 #define EDDSATAB(ed, ED, name)                                          \
1031   { #ed,                alg_##ed,       "" name " digital signatures" },
1032   EDDSAS(EDDSATAB)
1033 #undef EDDSATAB
1034   { "empty",            alg_empty,      "Empty parametrs-only key" },
1035   { 0,                  0 }
1036 };
1037
1038 /* --- @cmd_add@ --- */
1039
1040 static int cmd_add(int argc, char *argv[])
1041 {
1042   key_file f;
1043   time_t exp = KEXP_EXPIRE;
1044   uint32 kid = rand_global.ops->word(&rand_global);
1045   const char *tag = 0, *ptag = 0;
1046   const char *c = 0;
1047   keyalg *alg = algtab;
1048   const char *rtag = 0;
1049   const struct seedalg *sa = SEEDALG_DEFAULT;
1050   keyopts k = { 0, 0, DSTR_INIT, 0, 0, 0, 0, 0, 0 };
1051   const char *seed = 0;
1052   k.r = &rand_global;
1053
1054   /* --- Parse options for the subcommand --- */
1055
1056   for (;;) {
1057     static struct option opt[] = {
1058       { "algorithm",    OPTF_ARGREQ,    0,      'a' },
1059       { "bits",         OPTF_ARGREQ,    0,      'b' },
1060       { "qbits",        OPTF_ARGREQ,    0,      'B' },
1061       { "parameters",   OPTF_ARGREQ,    0,      'p' },
1062       { "expire",       OPTF_ARGREQ,    0,      'e' },
1063       { "comment",      OPTF_ARGREQ,    0,      'c' },
1064       { "tag",          OPTF_ARGREQ,    0,      't' },
1065       { "rand-id",      OPTF_ARGREQ,    0,      'R' },
1066       { "key-id",       OPTF_ARGREQ,    0,      'I' },
1067       { "curve",        OPTF_ARGREQ,    0,      'C' },
1068       { "seedalg",      OPTF_ARGREQ,    0,      'A' },
1069       { "seed",         OPTF_ARGREQ,    0,      's' },
1070       { "newseed",      OPTF_ARGREQ,    0,      'n' },
1071       { "public-exponent", OPTF_ARGREQ, 0,      'E' },
1072       { "lock",         0,              0,      'l' },
1073       { "quiet",        0,              0,      'q' },
1074       { "lim-lee",      0,              0,      'L' },
1075       { "subgroup",     0,              0,      'S' },
1076       { "kcdsa",        0,              0,      'K' },
1077       { 0,              0,              0,      0 }
1078     };
1079     int i = mdwopt(argc, argv, "+a:b:B:p:e:c:t:R:I:C:A:s:n:E:lqrLKS",
1080                    opt, 0, 0, 0);
1081     if (i < 0)
1082       break;
1083
1084     /* --- Handle the various options --- */
1085
1086     switch (i) {
1087
1088       /* --- Read an algorithm name --- */
1089
1090       case 'a': {
1091         keyalg *a;
1092         size_t sz = strlen(optarg);
1093
1094         if (strcmp(optarg, "list") == 0) {
1095           for (a = algtab; a->name; a++)
1096             printf("%-10s %s\n", a->name, a->help);
1097           return (0);
1098         }
1099
1100         alg = 0;
1101         for (a = algtab; a->name; a++) {
1102           if (strncmp(optarg, a->name, sz) == 0) {
1103             if (a->name[sz] == 0) {
1104               alg = a;
1105               break;
1106             } else if (alg)
1107               die(EXIT_FAILURE, "ambiguous algorithm name `%s'", optarg);
1108             else
1109               alg = a;
1110           }
1111         }
1112         if (!alg)
1113           die(EXIT_FAILURE, "unknown algorithm name `%s'", optarg);
1114       } break;
1115
1116       /* --- Bits must be nonzero and a multiple of 8 --- */
1117
1118       case 'b': {
1119         char *p;
1120         k.bits = strtoul(optarg, &p, 0);
1121         if (k.bits == 0 || *p != 0)
1122           die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1123       } break;
1124
1125       case 'B': {
1126         char *p;
1127         k.qbits = strtoul(optarg, &p, 0);
1128         if (k.qbits == 0 || *p != 0)
1129           die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1130       } break;
1131
1132       /* --- Parameter selection --- */
1133
1134       case 'p':
1135         ptag = optarg;
1136         break;
1137
1138       /* --- Expiry dates get passed to @get_date@ for parsing --- */
1139
1140       case 'e':
1141         if (strcmp(optarg, "forever") == 0)
1142           exp = KEXP_FOREVER;
1143         else {
1144           exp = get_date(optarg, 0);
1145           if (exp == -1)
1146             die(EXIT_FAILURE, "bad expiry date `%s'", optarg);
1147         }
1148         break;
1149
1150       /* --- Store comments without interpretation --- */
1151
1152       case 'c':
1153         if (key_chkcomment(optarg))
1154           die(EXIT_FAILURE, "bad comment string `%s'", optarg);
1155         c = optarg;
1156         break;
1157
1158       /* --- Elliptic curve parameters --- */
1159
1160       case 'C':
1161         k.curve = optarg;
1162         break;
1163
1164       /* --- Store tags --- */
1165
1166       case 't':
1167         if (key_chkident(optarg))
1168           die(EXIT_FAILURE, "bad tag string `%s'", optarg);
1169         tag = optarg;
1170         break;
1171       case 'r':
1172         k.f |= f_retag;
1173         break;
1174
1175       /* --- Seeding --- */
1176
1177       case 'A': {
1178         const struct seedalg *ss;
1179         if (strcmp(optarg, "list") == 0) {
1180           printf("Seed algorithms:\n");
1181           for (ss = seedtab; ss->p; ss++)
1182             printf("  %s\n", ss->p);
1183           exit(0);
1184         }
1185         if (seed) die(EXIT_FAILURE, "seed already set -- put -A first");
1186         sa = 0;
1187         for (ss = seedtab; ss->p; ss++) {
1188           if (strcmp(optarg, ss->p) == 0)
1189             sa = ss;
1190         }
1191         if (!sa)
1192           die(EXIT_FAILURE, "seed algorithm `%s' not known", optarg);
1193       } break;
1194
1195       case 's': {
1196         codec *c;
1197         int rc;
1198         dstr d = DSTR_INIT;
1199         if (seed) die(EXIT_FAILURE, "seed already set");
1200         c = base64_class.decoder(CDCF_IGNEQPAD);
1201         if ((rc = c->ops->code(c, optarg, strlen(optarg), &d)) != 0 ||
1202             (rc = c->ops->code(c, 0, 0, &d)) != 0)
1203           die(EXIT_FAILURE, "invalid seed base64: %s", codec_strerror(rc));
1204         c->ops->destroy(c);
1205         k.r = sa->gen(d.buf, d.len);
1206         seed = optarg;
1207         dstr_destroy(&d);
1208       } break;
1209
1210       case 'n': {
1211         codec *c;
1212         dstr d = DSTR_INIT;
1213         char *p;
1214         unsigned n = strtoul(optarg, &p, 0);
1215         if (n == 0 || *p != 0 || n % 8 != 0)
1216           die(EXIT_FAILURE, "bad seed length `%s'", optarg);
1217         if (seed) die(EXIT_FAILURE, "seed already set");
1218         n /= 8;
1219         p = xmalloc(n);
1220         rand_get(RAND_GLOBAL, p, n);
1221         c = base64_class.encoder(0, "", 0);
1222         c->ops->code(c, p, n, &d); c->ops->code(c, 0, 0, &d);
1223         c->ops->destroy(c);
1224         seed = d.buf;
1225         k.r = sa->gen(p, n);
1226       } break;
1227
1228       /* --- Key id --- */
1229
1230       case 'I': {
1231         char *p;
1232         unsigned long id;
1233
1234         errno = 0;
1235         id = strtoul(optarg, &p, 16);
1236         if (errno || *p || id > MASK32)
1237           die(EXIT_FAILURE, "bad key-id `%s'", optarg);
1238         kid = id;
1239       } break;
1240
1241       /* --- Public exponent --- */
1242
1243       case 'E': {
1244         char *p;
1245         k.e = mp_readstring(k.e, optarg, &p, 0);
1246         if (!k.e || *p || MP_CMP(k.e, <, MP_THREE) || MP_EVENP(k.e))
1247           die(EXIT_FAILURE, "bad exponent `%s'", optarg);
1248       } break;
1249
1250       /* --- Other flags --- */
1251
1252       case 'R':
1253         rtag = optarg;
1254         break;
1255       case 'l':
1256         k.f |= f_lock;
1257         break;
1258       case 'q':
1259         k.f |= f_quiet;
1260         break;
1261       case 'L':
1262         k.f |= f_limlee;
1263         break;
1264       case 'K':
1265         k.f |= f_kcdsa;
1266         break;
1267       case 'S':
1268         k.f |= f_subgroup;
1269         break;
1270
1271       /* --- Other things are bogus --- */
1272
1273       default:
1274         k.f |= f_bogus;
1275         break;
1276     }
1277   }
1278
1279   /* --- Various sorts of bogosity --- */
1280
1281   if ((k.f & f_bogus) || optind + 1 > argc) {
1282     die(EXIT_FAILURE,
1283         "Usage: add [OPTIONS] TYPE [ATTR...]");
1284   }
1285   if (key_chkident(argv[optind]))
1286     die(EXIT_FAILURE, "bad key type `%s'", argv[optind]);
1287
1288   /* --- Set up various bits of the state --- */
1289
1290   if (exp == KEXP_EXPIRE)
1291     exp = time(0) + 14 * 24 * 60 * 60;
1292
1293   /* --- Open the file and create the basic key block --- *
1294    *
1295    * Keep on generating keyids until one of them doesn't collide.
1296    */
1297
1298   doopen(&f, KOPEN_WRITE);
1299   k.kf = &f;
1300
1301   /* --- Key the generator --- */
1302
1303   keyrand(&f, rtag);
1304
1305   for (;;) {
1306     int err;
1307     if ((err = key_new(&f, kid, argv[optind], exp, &k.k)) == 0)
1308       break;
1309     else if (err != KERR_DUPID)
1310       die(EXIT_FAILURE, "error adding new key: %s", key_strerror(err));
1311   }
1312
1313   /* --- Set various simple attributes --- */
1314
1315   if (tag) {
1316     int err;
1317     key *kk;
1318     if (k.f & f_retag) {
1319       if ((kk = key_bytag(&f, tag)) != 0 &&
1320           kk->tag &&
1321           strcmp(kk->tag, tag) == 0)
1322         key_settag(&f, kk, 0);
1323     }
1324     if ((err = key_settag(&f, k.k, tag)) != 0)
1325       die(EXIT_FAILURE, "error setting key tag: %s", key_strerror(err));
1326   }
1327
1328   if (c) {
1329     int err = key_setcomment(&f, k.k, c);
1330     if (err)
1331       die(EXIT_FAILURE, "error setting key comment: %s", key_strerror(err));
1332   }
1333
1334   setattr(&f, k.k, argv + optind + 1);
1335   if (seed) {
1336     key_putattr(&f, k.k, "genseed", seed);
1337     key_putattr(&f, k.k, "seedalg", sa->p);
1338   }
1339
1340   key_fulltag(k.k, &k.tag);
1341
1342   /* --- Find the parameter key --- */
1343
1344   if (ptag && (k.p = key_bytag(&f, ptag)) == 0)
1345     die(EXIT_FAILURE, "parameter key `%s' not found", ptag);
1346
1347   /* --- Now generate the actual key data --- */
1348
1349   alg->proc(&k);
1350
1351   /* --- Done --- */
1352
1353   dstr_destroy(&k.tag);
1354   doclose(&f);
1355   return (0);
1356 }
1357
1358 /*----- Key listing -------------------------------------------------------*/
1359
1360 /* --- Listing options --- */
1361
1362 typedef struct listopts {
1363   const char *tfmt;                     /* Date format (@strftime@-style) */
1364   int v;                                /* Verbosity level */
1365   unsigned f;                           /* Various flags */
1366   time_t t;                             /* Time now (for key expiry) */
1367   key_filter kf;                        /* Filter for matching keys */
1368 } listopts;
1369
1370 /* --- Listing flags --- */
1371
1372 #define f_newline 2u                    /* Write newline before next entry */
1373 #define f_attr 4u                       /* Written at least one attribute */
1374 #define f_utc 8u                        /* Emit UTC time, not local time */
1375
1376 /* --- @showkeydata@ --- *
1377  *
1378  * Arguments:   @key_data *k@ = pointer to key to write
1379  *              @int ind@ = indentation level
1380  *              @listopts *o@ = listing options
1381  *              @dstr *d@ = tag string for this subkey
1382  *
1383  * Returns:     ---
1384  *
1385  * Use:         Emits a piece of key data in a human-readable format.
1386  */
1387
1388 static void showkeydata(key_data *k, int ind, listopts *o, dstr *d)
1389 {
1390 #define INDENT(i) do {                                                  \
1391   int _i;                                                               \
1392   for (_i = 0; _i < (i); _i++) {                                        \
1393     putchar(' ');                                                       \
1394   }                                                                     \
1395 } while (0)
1396
1397   switch (k->e & KF_ENCMASK) {
1398
1399     /* --- Binary key data --- *
1400      *
1401      * Emit as a simple hex dump.
1402      */
1403
1404     case KENC_BINARY: {
1405       const octet *p = k->u.k.k;
1406       const octet *l = p + k->u.k.sz;
1407       size_t sz = 0;
1408
1409       fputs(" {", stdout);
1410       while (p < l) {
1411         if (sz % 16 == 0) {
1412           putchar('\n');
1413           INDENT(ind + 2);
1414         } else if (sz % 8 == 0)
1415           fputs("  ", stdout);
1416         else
1417           putc(' ', stdout);
1418         printf("%02x", *p++);
1419         sz++;
1420       }
1421       putchar('\n');
1422       INDENT(ind);
1423       fputs("}\n", stdout);
1424     } break;
1425
1426     /* --- Encrypted data --- *
1427      *
1428      * If the user is sufficiently keen, ask for a passphrase and decrypt the
1429      * key.  Otherwise just say that it's encrypted and move on.
1430      */
1431
1432     case KENC_ENCRYPT:
1433       if (o->v <= 3)
1434         fputs(" encrypted\n", stdout);
1435       else {
1436         key_data *kd;
1437         if (key_punlock(&kd, k, d->buf))
1438           printf(" <failed to unlock %s>\n", d->buf);
1439         else {
1440           fputs(" encrypted", stdout);
1441           showkeydata(kd, ind, o, d);
1442           key_drop(kd);
1443         }
1444       }
1445       break;
1446
1447     /* --- Integer keys --- *
1448      *
1449      * Emit as a large integer in decimal.  This makes using the key in
1450      * `calc' or whatever easier.
1451      */
1452
1453     case KENC_MP:
1454       putchar(' ');
1455       mp_writefile(k->u.m, stdout, 10);
1456       putchar('\n');
1457       break;
1458
1459     /* --- Strings --- */
1460
1461     case KENC_STRING:
1462       printf(" `%s'\n", k->u.p);
1463       break;
1464
1465     /* --- Elliptic curve points --- */
1466
1467     case KENC_EC:
1468       if (EC_ATINF(&k->u.e))
1469         fputs(" inf\n", stdout);
1470       else {
1471         fputs(" 0x", stdout); mp_writefile(k->u.e.x, stdout, 16);
1472         fputs(", 0x", stdout); mp_writefile(k->u.e.y, stdout, 16);
1473         putchar('\n');
1474       }
1475       break;
1476
1477     /* --- Structured keys --- *
1478      *
1479      * Just iterate over the subkeys.
1480      */
1481
1482     case KENC_STRUCT: {
1483       key_subkeyiter i;
1484       const char *tag;
1485       size_t n = d->len;
1486
1487       fputs(" {\n", stdout);
1488       for (key_mksubkeyiter(&i, k); key_nextsubkey(&i, &tag, &k); ) {
1489         if (!key_match(k, &o->kf))
1490           continue;
1491         INDENT(ind + 2);
1492         printf("%s =", tag);
1493         d->len = n;
1494         dstr_putf(d, ".%s", tag);
1495         showkeydata(k, ind + 2, o, d);
1496       }
1497       INDENT(ind);
1498       fputs("}\n", stdout);
1499     } break;
1500   }
1501
1502 #undef INDENT
1503 }
1504
1505 /* --- @showkey@ --- *
1506  *
1507  * Arguments:   @key *k@ = pointer to key to show
1508  *              @listopts *o@ = pointer to listing options
1509  *
1510  * Returns:     ---
1511  *
1512  * Use:         Emits a listing of a particular key.
1513  */
1514
1515 static void showkey(key *k, listopts *o)
1516 {
1517   char ebuf[24], dbuf[24];
1518   struct tm *tm;
1519
1520   /* --- Skip the key if the filter doesn't match --- */
1521
1522   if (!key_match(k->k, &o->kf))
1523     return;
1524
1525   /* --- Sort out the expiry and deletion times --- */
1526
1527   if (KEY_EXPIRED(o->t, k->exp))
1528     strcpy(ebuf, "expired");
1529   else if (k->exp == KEXP_FOREVER)
1530     strcpy(ebuf, "forever");
1531   else {
1532     tm = (o->f & f_utc) ? gmtime(&k->exp) : localtime(&k->exp);
1533     strftime(ebuf, sizeof(ebuf), o->tfmt, tm);
1534   }
1535
1536   if (KEY_EXPIRED(o->t, k->del))
1537     strcpy(dbuf, "deleted");
1538   else if (k->del == KEXP_FOREVER)
1539     strcpy(dbuf, "forever");
1540   else {
1541     tm = (o->f & f_utc) ? gmtime(&k->del) : localtime(&k->del);
1542     strftime(dbuf, sizeof(dbuf), o->tfmt, tm);
1543   }
1544
1545   /* --- If in compact format, just display and quit --- */
1546
1547   if (!o->v) {
1548     if (!(o->f & f_newline)) {
1549       printf("%8s  %-20s  %-20s  %-10s  %s\n",
1550              "Id", "Tag", "Type", "Expire", "Delete");
1551     }
1552     printf("%08lx  %-20s  %-20s  %-10s  %s\n",
1553            (unsigned long)k->id, k->tag ? k->tag : "<none>",
1554            k->type, ebuf, dbuf);
1555     o->f |= f_newline;
1556     return;
1557   }
1558
1559   /* --- Display the standard header --- */
1560
1561   if (o->f & f_newline)
1562     fputc('\n', stdout);
1563   printf("keyid: %08lx\n", (unsigned long)k->id);
1564   printf("tag: %s\n", k->tag ? k->tag : "<none>");
1565   printf("type: %s\n", k->type);
1566   printf("expiry: %s\n", ebuf);
1567   printf("delete: %s\n", dbuf);
1568   printf("comment: %s\n", k->c ? k->c : "<none>");
1569
1570   /* --- Display the attributes --- */
1571
1572   if (o->v > 1) {
1573     key_attriter i;
1574     const char *av, *an;
1575
1576     o->f &= ~f_attr;
1577     printf("attributes:");
1578     for (key_mkattriter(&i, k); key_nextattr(&i, &an, &av); ) {
1579       printf("\n  %s = %s", an, av);
1580       o->f |= f_attr;
1581     }
1582     if (o->f & f_attr)
1583       fputc('\n', stdout);
1584     else
1585       puts(" <none>");
1586   }
1587
1588   /* --- If dumping requested, dump the raw key data --- */
1589
1590   if (o->v > 2) {
1591     dstr d = DSTR_INIT;
1592     fputs("key:", stdout);
1593     key_fulltag(k, &d);
1594     showkeydata(k->k, 0, o, &d);
1595     dstr_destroy(&d);
1596   }
1597
1598   o->f |= f_newline;
1599 }
1600
1601 /* --- @cmd_list@ --- */
1602
1603 static int cmd_list(int argc, char *argv[])
1604 {
1605   key_file f;
1606   key *k;
1607   listopts o = { 0, 0, 0, 0, { 0, 0 } };
1608
1609   /* --- Parse subcommand options --- */
1610
1611   for (;;) {
1612     static struct option opt[] = {
1613       { "quiet",        0,              0,      'q' },
1614       { "verbose",      0,              0,      'v' },
1615       { "utc",          0,              0,      'u' },
1616       { "filter",       OPTF_ARGREQ,    0,      'f' },
1617       { 0,              0,              0,      0 }
1618     };
1619     int i = mdwopt(argc, argv, "+uqvf:", opt, 0, 0, 0);
1620     if (i < 0)
1621       break;
1622
1623     switch (i) {
1624       case 'u':
1625         o.f |= f_utc;
1626         break;
1627       case 'q':
1628         if (o.v)
1629           o.v--;
1630         break;
1631       case 'v':
1632         o.v++;
1633         break;
1634       case 'f': {
1635         char *p;
1636         int e = key_readflags(optarg, &p, &o.kf.f, &o.kf.m);
1637         if (e || *p)
1638           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1639       } break;
1640       default:
1641         o.f |= f_bogus;
1642         break;
1643     }
1644   }
1645
1646   if (o.f & f_bogus)
1647     die(EXIT_FAILURE, "Usage: list [-uqv] [-f FILTER] [TAG...]");
1648
1649   /* --- Open the key file --- */
1650
1651   doopen(&f, KOPEN_READ);
1652   o.t = time(0);
1653
1654   /* --- Set up the time format --- */
1655
1656   if (!o.v)
1657     o.tfmt = "%Y-%m-%d";
1658   else if (o.f & f_utc)
1659     o.tfmt = "%Y-%m-%d %H:%M:%S UTC";
1660   else
1661     o.tfmt = "%Y-%m-%d %H:%M:%S %Z";
1662
1663   /* --- If specific keys were requested use them, otherwise do all --- *
1664    *
1665    * Some day, this might turn into a wildcard match.
1666    */
1667
1668   if (optind < argc) {
1669     do {
1670       if ((k = key_bytag(&f, argv[optind])) != 0)
1671         showkey(k, &o);
1672       else {
1673         moan("key `%s' not found", argv[optind]);
1674         o.f |= f_bogus;
1675       }
1676       optind++;
1677     } while (optind < argc);
1678   } else {
1679     key_iter i;
1680     for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1681       showkey(k, &o);
1682   }
1683
1684   /* --- Done --- */
1685
1686   doclose(&f);
1687   if (o.f & f_bogus)
1688     return (EXIT_FAILURE);
1689   else
1690     return (0);
1691 }
1692
1693 /*----- Command implementation --------------------------------------------*/
1694
1695 /* --- @cmd_expire@ --- */
1696
1697 static int cmd_expire(int argc, char *argv[])
1698 {
1699   key_file f;
1700   key *k;
1701   int i;
1702   int rc = 0;
1703
1704   if (argc < 2)
1705     die(EXIT_FAILURE, "Usage: expire TAG...");
1706   doopen(&f, KOPEN_WRITE);
1707   for (i = 1; i < argc; i++) {
1708     if ((k = key_bytag(&f, argv[i])) != 0)
1709       key_expire(&f, k);
1710     else {
1711       moan("key `%s' not found", argv[i]);
1712       rc = 1;
1713     }
1714   }
1715   doclose(&f);
1716   return (rc);
1717 }
1718
1719 /* --- @cmd_delete@ --- */
1720
1721 static int cmd_delete(int argc, char *argv[])
1722 {
1723   key_file f;
1724   key *k;
1725   int i;
1726   int rc = 0;
1727
1728   if (argc < 2)
1729     die(EXIT_FAILURE, "Usage: delete TAG...");
1730   doopen(&f, KOPEN_WRITE);
1731   for (i = 1; i < argc; i++) {
1732     if ((k = key_bytag(&f, argv[i])) != 0)
1733       key_delete(&f, k);
1734     else {
1735       moan("key `%s' not found", argv[i]);
1736       rc = 1;
1737     }
1738   }
1739   doclose(&f);
1740   return (rc);
1741 }
1742
1743 /* --- @cmd_setattr@ --- */
1744
1745 static int cmd_setattr(int argc, char *argv[])
1746 {
1747   key_file f;
1748   key *k;
1749
1750   if (argc < 3)
1751     die(EXIT_FAILURE, "Usage: setattr TAG ATTR...");
1752   doopen(&f, KOPEN_WRITE);
1753   if ((k = key_bytag(&f, argv[1])) == 0)
1754     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1755   setattr(&f, k, argv + 2);
1756   doclose(&f);
1757   return (0);
1758 }
1759
1760 /* --- @cmd_getattr@ --- */
1761
1762 static int cmd_getattr(int argc, char *argv[])
1763 {
1764   key_file f;
1765   key *k;
1766   dstr d = DSTR_INIT;
1767   const char *p;
1768
1769   if (argc != 3)
1770     die(EXIT_FAILURE, "Usage: getattr TAG ATTR");
1771   doopen(&f, KOPEN_READ);
1772   if ((k = key_bytag(&f, argv[1])) == 0)
1773     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1774   key_fulltag(k, &d);
1775   if ((p = key_getattr(&f, k, argv[2])) == 0)
1776     die(EXIT_FAILURE, "no attribute `%s' for key `%s'", argv[2], d.buf);
1777   puts(p);
1778   dstr_destroy(&d);
1779   doclose(&f);
1780   return (0);
1781 }
1782
1783 /* --- @cmd_finger@ --- */
1784
1785 static const struct fpres {
1786   const char *name;
1787   const codec_class *cdc;
1788   unsigned short ival;
1789   const char *sep;
1790 } fprestab[] = {
1791   { "hex", &hex_class, 8, "-:" },
1792   { "base32", &base32_class, 6, ":" },
1793   { 0, 0 }
1794 };
1795
1796 static void fingerprint(key *k, const struct fpres *fpres,
1797                         const gchash *ch, const key_filter *kf)
1798 {
1799   ghash *h;
1800   dstr d = DSTR_INIT, dd = DSTR_INIT;
1801   const octet *p;
1802   size_t i;
1803   codec *c;
1804
1805   h = GH_INIT(ch);
1806   if (key_fingerprint(k, h, kf)) {
1807     p = GH_DONE(h, 0);
1808     c = fpres->cdc->encoder(CDCF_LOWERC | CDCF_NOEQPAD, "", 0);
1809     c->ops->code(c, p, ch->hashsz, &dd); c->ops->code(c, 0, 0, &dd);
1810     c->ops->destroy(c);
1811     for (i = 0; i < dd.len; i++) {
1812       if (i && i%fpres->ival == 0) dstr_putc(&d, fpres->sep[0]);
1813       dstr_putc(&d, dd.buf[i]);
1814     }
1815     dstr_putc(&d, ' '); key_fulltag(k, &d); dstr_putc(&d, '\n');
1816     dstr_write(&d, stdout);
1817   }
1818   dstr_destroy(&d); dstr_destroy(&dd);
1819   GH_DESTROY(h);
1820 }
1821
1822 static const struct fpres *lookup_fpres(const char *name)
1823 {
1824   const struct fpres *fpres;
1825   for (fpres = fprestab; fpres->name; fpres++)
1826     if (strcmp(fpres->name, name) == 0) return (fpres);
1827   die(EXIT_FAILURE, "unknown presentation syle `%s'", name);
1828 }
1829
1830 static int cmd_finger(int argc, char *argv[])
1831 {
1832   key_file f;
1833   int rc = 0;
1834   const struct fpres *fpres = fprestab;
1835   const gchash *ch = &rmd160;
1836   key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1837
1838   for (;;) {
1839     static struct option opt[] = {
1840       { "filter",       OPTF_ARGREQ,    0,      'f' },
1841       { "presentation", OPTF_ARGREQ,    0,      'p' },
1842       { "algorithm",    OPTF_ARGREQ,    0,      'a' },
1843       { 0,              0,              0,      0 }
1844     };
1845     int i = mdwopt(argc, argv, "+f:a:p:", opt, 0, 0, 0);
1846     if (i < 0)
1847       break;
1848     switch (i) {
1849       case 'f': {
1850         char *p;
1851         int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1852         if (err || *p)
1853           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1854       } break;
1855       case 'p':
1856         fpres = lookup_fpres(optarg);
1857         break;
1858       case 'a':
1859         if ((ch = ghash_byname(optarg)) == 0)
1860           die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1861         break;
1862       default:
1863         rc = 1;
1864         break;
1865     }
1866   }
1867
1868   argv += optind; argc -= optind;
1869   if (rc) {
1870     die(EXIT_FAILURE,
1871         "Usage: fingerprint [-a HASHALG] [-p STYLE] [-f FILTER] [TAG...]");
1872   }
1873
1874   doopen(&f, KOPEN_READ);
1875
1876   if (argc) {
1877     int i;
1878     for (i = 0; i < argc; i++) {
1879       key *k = key_bytag(&f, argv[i]);
1880       if (k)
1881         fingerprint(k, fpres, ch, &kf);
1882       else {
1883         rc = 1;
1884         moan("key `%s' not found", argv[i]);
1885       }
1886     }
1887   } else {
1888     key_iter i;
1889     key *k;
1890     for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1891       fingerprint(k, fpres, ch, &kf);
1892   }
1893   return (rc);
1894 }
1895
1896 /* --- @cmd_verify@ --- */
1897
1898 static int cmd_verify(int argc, char *argv[])
1899 {
1900   key_file f;
1901   int rc = 0;
1902   const gchash *ch = &rmd160;
1903   ghash *h;
1904   key *k;
1905   const octet *fpr;
1906   dstr d = DSTR_INIT, dd = DSTR_INIT;
1907   codec *c;
1908   const char *p;
1909   const struct fpres *fpres = fprestab;
1910   key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1911
1912   for (;;) {
1913     static struct option opt[] = {
1914       { "filter",       OPTF_ARGREQ,    0,      'f' },
1915       { "presentation", OPTF_ARGREQ,    0,      'p' },
1916       { "algorithm",    OPTF_ARGREQ,    0,      'a' },
1917       { 0,              0,              0,      0 }
1918     };
1919     int i = mdwopt(argc, argv, "+f:a:p:", opt, 0, 0, 0);
1920     if (i < 0)
1921       break;
1922     switch (i) {
1923       case 'f': {
1924         char *p;
1925         int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1926         if (err || *p)
1927           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1928       } break;
1929       case 'p':
1930         fpres = lookup_fpres(optarg);
1931         break;
1932       case 'a':
1933         if ((ch = ghash_byname(optarg)) == 0)
1934           die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1935         break;
1936       default:
1937         rc = 1;
1938         break;
1939     }
1940   }
1941
1942   argv += optind; argc -= optind;
1943   if (rc || argc != 2) {
1944     die(EXIT_FAILURE,
1945         "Usage: verify [-a HASHALG] [-p STYLE] [-f FILTER] TAG FINGERPRINT");
1946   }
1947
1948   doopen(&f, KOPEN_READ);
1949
1950   if ((k = key_bytag(&f, argv[0])) == 0)
1951     die(EXIT_FAILURE, "key `%s' not found", argv[0]);
1952   for (p = argv[1]; *p; p++) {
1953     if (strchr(fpres->sep, *p)) continue;
1954     dstr_putc(&dd, *p);
1955   }
1956   c = fpres->cdc->decoder(CDCF_IGNCASE | CDCF_IGNEQPAD |
1957                           CDCF_IGNSPC | CDCF_IGNNEWL);
1958   if ((rc = c->ops->code(c, dd.buf, dd.len, &d)) != 0 ||
1959       (rc = c->ops->code(c, 0, 0, &d)) != 0)
1960     die(EXIT_FAILURE, "invalid fingerprint: %s", codec_strerror(rc));
1961   c->ops->destroy(c);
1962   if (d.len != ch->hashsz) {
1963     die(EXIT_FAILURE, "incorrect fingerprint length (%lu != %lu)",
1964         (unsigned long)d.len, (unsigned long)ch->hashsz);
1965   }
1966   h = GH_INIT(ch);
1967   if (!key_fingerprint(k, h, &kf))
1968     die(EXIT_FAILURE, "key has no fingerprintable components (as filtered)");
1969   fpr = GH_DONE(h, 0);
1970   if (memcmp(fpr, d.buf, ch->hashsz) != 0)
1971     die(EXIT_FAILURE, "key fingerprint mismatch");
1972   dstr_destroy(&d); dstr_destroy(&dd);
1973   doclose(&f);
1974   return (0);
1975 }
1976
1977 /* --- @cmd_comment@ --- */
1978
1979 static int cmd_comment(int argc, char *argv[])
1980 {
1981   key_file f;
1982   key *k;
1983   int err;
1984
1985   if (argc < 2 || argc > 3)
1986     die(EXIT_FAILURE, "Usage: comment TAG [COMMENT]");
1987   doopen(&f, KOPEN_WRITE);
1988   if ((k = key_bytag(&f, argv[1])) == 0)
1989     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1990   if ((err = key_setcomment(&f, k, argv[2])) != 0)
1991     die(EXIT_FAILURE, "bad comment `%s': %s", argv[2], key_strerror(err));
1992   doclose(&f);
1993   return (0);
1994 }
1995
1996 /* --- @cmd_tag@ --- */
1997
1998 static int cmd_tag(int argc, char *argv[])
1999 {
2000   key_file f;
2001   key *k;
2002   int err;
2003   unsigned flags = 0;
2004   int rc = 0;
2005
2006   for (;;) {
2007     static struct option opt[] = {
2008       { "retag",        0,              0,      'r' },
2009       { 0,              0,              0,      0 }
2010     };
2011     int i = mdwopt(argc, argv, "+r", opt, 0, 0, 0);
2012     if (i < 0)
2013       break;
2014     switch (i) {
2015       case 'r':
2016         flags |= f_retag;
2017         break;
2018       default:
2019         rc = 1;
2020         break;
2021     }
2022   }
2023
2024   argv += optind; argc -= optind;
2025   if (argc < 1 || argc > 2 || rc)
2026     die(EXIT_FAILURE, "Usage: tag [-r] TAG [NEW-TAG]");
2027   doopen(&f, KOPEN_WRITE);
2028   if (flags & f_retag) {
2029     if ((k = key_bytag(&f, argv[1])) != 0 && strcmp(k->tag, argv[1]) == 0)
2030       key_settag(&f, k, 0);
2031   }
2032   if ((k = key_bytag(&f, argv[0])) == 0)
2033     die(EXIT_FAILURE, "key `%s' not found", argv[0]);
2034   if ((err = key_settag(&f, k, argv[1])) != 0)
2035     die(EXIT_FAILURE, "bad tag `%s': %s", argv[1], key_strerror(err));
2036   doclose(&f);
2037   return (0);
2038 }
2039
2040 /* --- @cmd_lock@ --- */
2041
2042 static int cmd_lock(int argc, char *argv[])
2043 {
2044   key_file f;
2045   key *k;
2046   key_data **kd;
2047   dstr d = DSTR_INIT;
2048
2049   if (argc != 2)
2050     die(EXIT_FAILURE, "Usage: lock QTAG");
2051   doopen(&f, KOPEN_WRITE);
2052   if (key_qtag(&f, argv[1], &d, &k, &kd))
2053     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
2054   if ((*kd)->e == KENC_ENCRYPT && key_punlock(kd, 0, d.buf))
2055     die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
2056   if (key_plock(kd, 0, d.buf))
2057     die(EXIT_FAILURE, "failed to lock key `%s'", d.buf);
2058   f.f |= KF_MODIFIED;
2059   doclose(&f);
2060   return (0);
2061 }
2062
2063 /* --- @cmd_unlock@ --- */
2064
2065 static int cmd_unlock(int argc, char *argv[])
2066 {
2067   key_file f;
2068   key *k;
2069   key_data **kd;
2070   dstr d = DSTR_INIT;
2071
2072   if (argc != 2)
2073     die(EXIT_FAILURE, "Usage: unlock QTAG");
2074   doopen(&f, KOPEN_WRITE);
2075   if (key_qtag(&f, argv[1], &d, &k, &kd))
2076     die(EXIT_FAILURE, "key `%s' not found", argv[1]);
2077   if ((*kd)->e != KENC_ENCRYPT)
2078     die(EXIT_FAILURE, "key `%s' is not encrypted", d.buf);
2079   if (key_punlock(kd, 0, d.buf))
2080     die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
2081   f.f |= KF_MODIFIED;
2082   doclose(&f);
2083   return (0);
2084 }
2085
2086 /* --- @cmd_extract@ --- */
2087
2088 static int cmd_extract(int argc, char *argv[])
2089 {
2090   key_file f;
2091   key *k;
2092   int i;
2093   int rc = 0;
2094   key_filter kf = { 0, 0 };
2095   dstr d = DSTR_INIT;
2096   const char *outfile = 0;
2097   FILE *fp;
2098
2099   for (;;) {
2100     static struct option opt[] = {
2101       { "filter",       OPTF_ARGREQ,    0,      'f' },
2102       { 0,              0,              0,      0 }
2103     };
2104     int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
2105     if (i < 0)
2106       break;
2107     switch (i) {
2108       case 'f': {
2109         char *p;
2110         int err = key_readflags(optarg, &p, &kf.f, &kf.m);
2111         if (err || *p)
2112           die(EXIT_FAILURE, "bad filter string `%s'", optarg);
2113       } break;
2114       default:
2115         rc = 1;
2116         break;
2117     }
2118   }
2119
2120   argv += optind; argc -= optind;
2121   if (rc || argc < 1)
2122     die(EXIT_FAILURE, "Usage: extract [-f FILTER] FILE [TAG...]");
2123   if (strcmp(*argv, "-") == 0)
2124     fp = stdout;
2125   else {
2126     outfile = *argv;
2127     dstr_putf(&d, "%s.new", outfile);
2128     if (!(fp = fopen(d.buf, "w"))) {
2129       die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
2130           d.buf, strerror(errno));
2131     }
2132   }
2133
2134   doopen(&f, KOPEN_READ);
2135   if (argc < 2) {
2136     key_iter i;
2137     key *k;
2138     for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
2139       key_extract(&f, k, fp, &kf);
2140   } else {
2141     for (i = 1; i < argc; i++) {
2142       if ((k = key_bytag(&f, argv[i])) != 0)
2143         key_extract(&f, k, fp, &kf);
2144       else {
2145         moan("key `%s' not found", argv[i]);
2146         rc = 1;
2147       }
2148     }
2149   }
2150   if (fclose(fp) || (outfile && rename(d.buf, outfile)))
2151     die(EXIT_FAILURE, "error writing file: %s", strerror(errno));
2152   dstr_destroy(&d);
2153   doclose(&f);
2154   return (rc);
2155 }
2156
2157 /* --- @cmd_tidy@ --- */
2158
2159 static int cmd_tidy(int argc, char *argv[])
2160 {
2161   key_file f;
2162   if (argc != 1)
2163     die(EXIT_FAILURE, "Usage: tidy");
2164   doopen(&f, KOPEN_WRITE);
2165   f.f |= KF_MODIFIED; /* Nasty hack */
2166   doclose(&f);
2167   return (0);
2168 }
2169
2170 /* --- @cmd_merge@ --- */
2171
2172 static int cmd_merge(int argc, char *argv[])
2173 {
2174   key_file f;
2175   FILE *fp;
2176
2177   if (argc != 2)
2178     die(EXIT_FAILURE, "Usage: merge FILE");
2179   if (strcmp(argv[1], "-") == 0)
2180     fp = stdin;
2181   else if (!(fp = fopen(argv[1], "r"))) {
2182     die(EXIT_FAILURE, "couldn't open `%s' for reading: %s",
2183         argv[1], strerror(errno));
2184   }
2185
2186   doopen(&f, KOPEN_WRITE);
2187   key_merge(&f, argv[1], fp, key_moan, 0);
2188   doclose(&f);
2189   return (0);
2190 }
2191
2192 /* --- @cmd_show@ --- */
2193
2194 #define LISTS(LI)                                                       \
2195   LI("Lists", list,                                                     \
2196      listtab[i].name, listtab[i].name)                                  \
2197   LI("Hash functions", hash,                                            \
2198      ghashtab[i], ghashtab[i]->name)                                    \
2199   LI("Elliptic curves", ec,                                             \
2200      ectab[i].name, ectab[i].name)                                      \
2201   LI("Prime Diffie-Hellman groups", dh,                                 \
2202      ptab[i].name, ptab[i].name)                                        \
2203   LI("Binary Diffie-Hellman groups", bindh,                             \
2204      bintab[i].name, bintab[i].name)                                    \
2205   LI("Key-generation algorithms", keygen,                               \
2206      algtab[i].name, algtab[i].name)                                    \
2207   LI("Random seeding algorithms", seed,                                 \
2208      seedtab[i].p, seedtab[i].p)                                        \
2209   LI("Fingerprint presentation styles", fpres,                          \
2210      fprestab[i].name, fprestab[i].name)
2211
2212 MAKELISTTAB(listtab, LISTS)
2213
2214 static int cmd_show(int argc, char *argv[])
2215 {
2216   return (displaylists(listtab, argv + 1));
2217 }
2218
2219 /*----- Main command table ------------------------------------------------*/
2220
2221 static int cmd_help(int argc, char *argv[]);
2222
2223 static cmd cmds[] = {
2224   { "help", cmd_help, "help [COMMAND...]" },
2225   { "show", cmd_show, "show [ITEM...]" },
2226   { "list", cmd_list, "list [-uqv] [-f FILTER] [TAG...]", "\
2227 Options:\n\
2228 \n\
2229 -u, --utc               Display expiry times etc. in UTC, not local time.\n\
2230 -q, --quiet             Show less information.\n\
2231 -v, --verbose           Show more information.\n\
2232 " },
2233   { "fingerprint", cmd_finger,
2234     "fingerprint [-a HASHALG] [-p STYLE] [-f FILTER] [TAG...]", "\
2235 Options:\n\
2236 \n\
2237 -f, --filter=FILT       Only hash key components matching FILT.\n\
2238 -p, --presentation=STYLE Use STYLE for presenting fingerprints.\n\
2239 -a, --algorithm=HASH    Use the named HASH algorithm.\n\
2240                           ($ show hash for list.)\n\
2241 " },
2242   { "verify", cmd_verify,
2243     "verify [-a HASH] [-p STYLE] [-f FILTER] TAG FINGERPRINT", "\
2244 Options:\n\
2245 \n\
2246 -f, --filter=FILT       Only hash key components matching FILT.\n\
2247 -p, --presentation=STYLE Expect FINGERPRINT in the given STYLE.\n\
2248 -a, --algorithm=HASH    Use the named HASH algorithm.\n\
2249                           ($ show hash for list.)\n\
2250 " },
2251   { "extract", cmd_extract, "extract [-f FILTER] FILE [TAG...]", "\
2252 Options:\n\
2253 \n\
2254 -f, --filter=FILT       Only extract key components matching FILT.\n\
2255 " },
2256   { "merge", cmd_merge, "merge FILE" },
2257   { "expire", cmd_expire, "expire TAG..." },
2258   { "delete", cmd_delete, "delete TAG..." },
2259   { "setattr", cmd_setattr, "setattr TAG ATTR..." },
2260   { "getattr", cmd_getattr, "getattr TAG ATTR" },
2261   { "comment", cmd_comment, "comment TAG [COMMENT]" },
2262   { "lock", cmd_lock, "lock QTAG" },
2263   { "unlock", cmd_unlock, "unlock QTAG" },
2264   { "tag", cmd_tag, "tag [-r] TAG [NEW-TAG]", "\
2265 Options:\n\
2266 \n\
2267 -r, --retag             Untag any key currently called new-tag.\n\
2268 " },
2269   { "tidy", cmd_tidy, "tidy" },
2270   { "add", cmd_add,
2271     "add [-OPTIONS] TYPE [ATTR...]\n\
2272         Options: [-lqrLKS] [-a ALG] [-bB BITS] [-p PARAM] [-R TAG]\n\
2273                  [-A SEEDALG] [-s SEED] [-n BITS] [-I KEYID]\n\
2274                  [-e EXPIRE] [-t TAG] [-c COMMENT]", "\
2275 Options:\n\
2276 \n\
2277 -a, --algorithm=ALG     Generate keys suitable for ALG.\n\
2278                           ($ show keygen for list.)\n\
2279 -b, --bits=N            Generate an N-bit key.\n\
2280 -B, --qbits=N           Use an N-bit subgroup or factors.\n\
2281 -p, --parameters=TAG    Get group parameters from TAG.\n\
2282 -C, --curve=NAME        Use elliptic curve or DH group NAME.\n\
2283                           ($ show ec or $ show dh for list.)\n\
2284 -A, --seedalg=ALG       Use pseudorandom generator ALG to generate key.\n\
2285                           ($ show seed for list.)\n\
2286 -s, --seed=BASE64       Use Base64-encoded string BASE64 as seed.\n\
2287 -n, --newseed=COUNT     Generate new COUNT-bit seed.\n\
2288 -e, --expire=TIME       Make the key expire after TIME.\n\
2289 -c, --comment=STRING    Attach the command STRING to the key.\n\
2290 -t, --tag=TAG           Tag the key with the name TAG.\n\
2291 -r, --retag             Untag any key currently with that tag.\n\
2292 -R, --rand-id=TAG       Use key named TAG for the random number generator.\n\
2293 -I, --key-id=ID         Force the key-id for the new key.\n\
2294 -l, --lock              Lock the generated key with a passphrase.\n\
2295 -q, --quiet             Don't give progress indicators while working.\n\
2296 -L, --lim-lee           Generate Lim-Lee primes for Diffie-Hellman groups.\n\
2297 -K, --kcdsa             Generate KCDSA-style Lim-Lee primes for DH groups.\n\
2298 -S, --subgroup          Use a prime-order subgroup for Diffie-Hellman.\n\
2299 " },
2300   { 0, 0, 0 }
2301 };
2302
2303 static int cmd_help(int argc, char *argv[])
2304 {
2305   sc_help(cmds, stdout, argv + 1);
2306   return (0);
2307 }
2308
2309 /*----- Main code ---------------------------------------------------------*/
2310
2311 /* --- Helpful GNUy functions --- */
2312
2313 static void usage(FILE *fp)
2314 {
2315   pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
2316 }
2317
2318 void version(FILE *fp)
2319 {
2320   pquis(fp, "$, Catacomb version " VERSION "\n");
2321 }
2322
2323 void help_global(FILE *fp)
2324 {
2325   usage(fp);
2326   fputs("\n\
2327 Performs various simple key management operations.\n\
2328 \n\
2329 Global command line options:\n\
2330 \n\
2331 -h, --help [COMMAND...] Display this help text (or help for COMMANDs).\n\
2332 -v, --version           Display version number.\n\
2333 -u, --usage             Display short usage summary.\n\
2334 \n\
2335 -k, --keyring=FILE      Read and write keys in FILE.\n",
2336         fp);
2337 }
2338
2339 /* --- @main@ --- *
2340  *
2341  * Arguments:   @int argc@ = number of command line arguments
2342  *              @char *argv[]@ = array of command line arguments
2343  *
2344  * Returns:     Nonzero on failure.
2345  *
2346  * Use:         Main program.  Performs simple key management functions.
2347  */
2348
2349 int main(int argc, char *argv[])
2350 {
2351   unsigned f = 0;
2352
2353 #define f_bogus 1u
2354
2355   /* --- Initialization --- */
2356
2357   ego(argv[0]);
2358   sub_init();
2359
2360   /* --- Parse command line options --- */
2361
2362   for (;;) {
2363     static struct option opt[] = {
2364
2365       /* --- Standard GNUy help options --- */
2366
2367       { "help",         0,              0,      'h' },
2368       { "version",      0,              0,      'v' },
2369       { "usage",        0,              0,      'u' },
2370
2371       /* --- Real live useful options --- */
2372
2373       { "keyring",      OPTF_ARGREQ,    0,      'k' },
2374
2375       /* --- Magic terminator --- */
2376
2377       { 0,              0,              0,      0 }
2378     };
2379     int i = mdwopt(argc, argv, "+hvu k:", opt, 0, 0, 0);
2380
2381     if (i < 0)
2382       break;
2383     switch (i) {
2384
2385       /* --- GNU help options --- */
2386
2387       case 'h':
2388         sc_help(cmds, stdout, argv + optind);
2389         exit(0);
2390       case 'v':
2391         version(stdout);
2392         exit(0);
2393       case 'u':
2394         usage(stdout);
2395         exit(0);
2396
2397       /* --- Real useful options --- */
2398
2399       case 'k':
2400         keyfile = optarg;
2401         break;
2402
2403       /* --- Bogosity --- */
2404
2405       default:
2406         f |= f_bogus;
2407         break;
2408     }
2409   }
2410
2411   /* --- Complain about excessive bogons --- */
2412
2413   if (f & f_bogus || optind == argc) {
2414     usage(stderr);
2415     exit(1);
2416   }
2417
2418   /* --- Initialize the Catacomb random number generator --- */
2419
2420   rand_noisesrc(RAND_GLOBAL, &noise_source);
2421   rand_seed(RAND_GLOBAL, 160);
2422
2423   /* --- Dispatch to appropriate command handler --- */
2424
2425   argc -= optind;
2426   argv += optind;
2427   optind = 0;
2428   return (findcmd(cmds, argv[0])->cmd(argc, argv));
2429 }
2430
2431 /*----- That's all, folks -------------------------------------------------*/