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