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