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