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