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