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