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