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