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