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