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