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