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