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