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