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