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