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