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