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