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