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