3 * Simple key manager program
5 * (c) 1999 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
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.
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.
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,
28 /*----- Header files ------------------------------------------------------*/
30 #define _FILE_OFFSET_BITS 64
41 #include <mLib/codec.h>
42 #include <mLib/base32.h>
43 #include <mLib/base64.h>
45 #include <mLib/mdwopt.h>
46 #include <mLib/quis.h>
47 #include <mLib/report.h>
79 #include "sha256-mgf.h"
80 #include "sha224-mgf.h"
81 #include "sha384-mgf.h"
82 #include "sha512-mgf.h"
83 #include "tiger-mgf.h"
84 #include "rmd128-mgf.h"
85 #include "rmd160-mgf.h"
86 #include "rmd256-mgf.h"
87 #include "rmd320-mgf.h"
91 /*----- Handy global state ------------------------------------------------*/
93 static const char *keyfile = "keyring";
95 /*----- Useful shared functions -------------------------------------------*/
99 * Arguments: @key_file *f@ = pointer to key file block
100 * @unsigned how@ = method to open file with
104 * Use: Opens a key file and handles errors by panicking
108 static void doopen(key_file *f, unsigned how)
110 if (key_open(f, keyfile, how, key_moan, 0)){
111 die(EXIT_FAILURE, "couldn't open keyring `%s': %s",
112 keyfile, strerror(errno));
116 /* --- @doclose@ --- *
118 * Arguments: @key_file *f@ = pointer to key file block
122 * Use: Closes a key file and handles errors by panicking
126 static void doclose(key_file *f)
128 switch (key_close(f)) {
130 die(EXIT_FAILURE, "couldn't write file `%s': %s",
131 keyfile, strerror(errno));
133 die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
134 keyfile, strerror(errno));
138 /* --- @setattr@ --- *
140 * Arguments: @key_file *f@ = pointer to key file block
141 * @key *k@ = pointer to key block
142 * @char *v[]@ = array of assignments (overwritten!)
146 * Use: Applies the attribute assignments to the key.
149 static void setattr(key_file *f, key *k, char *v[])
154 size_t eq = strcspn(p, "=");
156 moan("invalid assignment: `%s' (ignored)", p);
162 if ((err = key_putattr(f, k, *v, *p ? p : 0)) != 0)
163 die(EXIT_FAILURE, "couldn't set attributes: %s", key_strerror(err));
168 /*----- Seeding -----------------------------------------------------------*/
170 const struct seedalg { const char *p; grand *(*gen)(const void *, size_t); }
172 { "dsarand", dsarand_create },
173 { "rmd128-mgf", rmd128_mgfrand },
174 { "rmd160-mgf", rmd160_mgfrand },
175 { "rmd256-mgf", rmd256_mgfrand },
176 { "rmd320-mgf", rmd320_mgfrand },
177 { "sha-mgf", sha_mgfrand },
178 { "sha224-mgf", sha224_mgfrand },
179 { "sha256-mgf", sha256_mgfrand },
180 { "sha384-mgf", sha384_mgfrand },
181 { "sha512-mgf", sha512_mgfrand },
182 { "tiger-mgf", tiger_mgfrand },
186 #define SEEDALG_DEFAULT (seedtab + 2)
188 /*----- Key generation ----------------------------------------------------*/
190 /* --- Key generation parameters --- */
192 typedef struct keyopts {
193 key_file *kf; /* Pointer to key file */
194 key *k; /* Pointer to the actual key */
195 dstr tag; /* Full tag name for the key */
196 unsigned f; /* Flags for the new key */
197 unsigned bits, qbits; /* Bit length for the new key */
198 const char *curve; /* Elliptic curve name/info */
199 grand *r; /* Random number source */
200 mp *e; /* Public exponent */
201 key *p; /* Parameters key-data */
204 #define f_bogus 1u /* Error in parsing */
205 #define f_lock 2u /* Passphrase-lock private key */
206 #define f_quiet 4u /* Don't show a progress indicator */
207 #define f_limlee 8u /* Generate Lim-Lee primes */
208 #define f_subgroup 16u /* Generate a subgroup */
209 #define f_retag 32u /* Remove any existing tag */
210 #define f_kcdsa 64u /* Generate KCDSA primes */
212 /* --- @dolock@ --- *
214 * Arguments: @keyopts *k@ = key generation options
215 * @key_data **kd@ = pointer to key data to lock
216 * @const char *t@ = tag suffix or null
220 * Use: Does passphrase locking on new keys.
223 static void dolock(keyopts *k, key_data **kd, const char *t)
225 if (!(k->f & f_lock))
228 dstr_putf(&k->tag, ".%s", t);
229 if (key_plock(kd, 0, k->tag.buf))
230 die(EXIT_FAILURE, "couldn't lock key");
233 /* --- @copyparam@ --- *
235 * Arguments: @keyopts *k@ = pointer to key options
236 * @const char **pp@ = checklist of parameters, or null
238 * Returns: Nonzero if parameters copied; zero if you have to generate
241 * Use: Copies parameters from a source key to the current one.
244 static int copyparam(keyopts *k, const char **pp)
255 /* --- Quick check if no parameters supplied --- */
260 /* --- Copy the key data if there's anything we want --- */
264 /* --- Run through the checklist --- */
266 key_fulltag(k->p, &t);
267 if ((k->p->k->e & KF_ENCMASK) != KENC_STRUCT)
268 die(EXIT_FAILURE, "parameter key `%s' is not structured", t.buf);
270 key_data *kd = key_structfind(k->p->k, *pp);
273 "bad parameter key `%s': parameter `%s' not found", t.buf, *pp);
275 if (!KEY_MATCH(kd, &kf)) {
277 "bad parameter key `%s': subkey `%s' is not shared", t.buf, *pp);
282 /* --- Copy over the parameters --- */
284 kd = key_copydata(k->p->k, &kf);
286 key_setkeydata(k->kf, k->k, kd);
290 /* --- Copy over attributes --- */
292 for (key_mkattriter(&i, k->p); key_nextattr(&i, &n, &v); )
293 key_putattr(k->kf, k->k, n, v);
303 * Arguments: @key_data *k@ = pointer to key data block
304 * @const char *tag@ = tag string to use
306 * Returns: Pointer to multiprecision integer key item.
308 * Use: Fetches an MP key component.
311 static mp *getmp(key_data *k, const char *tag)
313 k = key_structfind(k, tag);
315 die(EXIT_FAILURE, "unexpected failure looking up subkey `%s'", tag);
316 if ((k->e & KF_ENCMASK) != KENC_MP)
317 die(EXIT_FAILURE, "subkey `%s' has an incompatible type", tag);
321 /* --- @keyrand@ --- *
323 * Arguments: @key_file *kf@ = pointer to key file
324 * @const char *id@ = pointer to key id (or null)
328 * Use: Keys the random number generator.
331 static void keyrand(key_file *kf, const char *id)
335 /* --- Find the key --- */
338 if ((k = key_bytag(kf, id)) == 0)
339 die(EXIT_FAILURE, "key `%s' not found", id);
341 k = key_bytype(kf, "catacomb-rand");
344 key_data *kd = k->k, *kkd;
348 switch (kd->e & KF_ENCMASK) {
354 if (key_punlock(&kkd, kd, d.buf))
355 die(EXIT_FAILURE, "error unlocking key `%s'", d.buf);
363 die(EXIT_FAILURE, "bad encoding type for key `%s'", d.buf);
367 /* --- Key the generator --- */
369 rand_key(RAND_GLOBAL, kd->u.k.k, kd->u.k.sz);
374 /* --- Key generation algorithms --- */
376 static void alg_empty(keyopts *k)
379 key_setkeydata(k->kf, k->k,
380 key_newstring(KCAT_SHARE, k->curve ? k->curve : "."));
383 static void alg_binary(keyopts *k)
394 sz = (k->bits + 7) >> 3;
396 m = (1 << (((k->bits - 1) & 7) + 1)) - 1;
397 k->r->ops->fill(k->r, p, sz);
399 kd = key_newbinary(KCAT_SYMM | KF_BURN, p, sz);
402 key_setkeydata(k->kf, k->k, kd);
407 static void alg_des(keyopts *k)
417 if (k->bits % 56 || k->bits > 168)
418 die(EXIT_FAILURE, "DES keys must be 56, 112 or 168 bits long");
422 k->r->ops->fill(k->r, p, sz);
423 for (i = 0; i < sz; i++) {
424 octet x = p[i] | 0x01;
428 p[i] = (p[i] & 0xfe) | (x & 0x01);
430 kd = key_newbinary(KCAT_SYMM | KF_BURN, p, sz);
433 key_setkeydata(k->kf, k->k, kd);
438 static void alg_rsa(keyopts *k)
443 /* --- Sanity checking --- */
449 die(EXIT_FAILURE, "RSA key too tiny");
451 k->e = mp_fromulong(MP_NEW, 65537);
453 /* --- Generate the RSA parameters --- */
455 if (rsa_gen_e(&rp, k->bits, k->e, k->r, 0,
456 (k->f & f_quiet) ? 0 : pgen_ev, 0))
457 die(EXIT_FAILURE, "RSA key generation failed");
459 /* --- Run a test encryption --- */
462 grand *g = fibrand_create(k->r->ops->word(k->r));
464 mp *m = mprand_range(MP_NEW, rp.n, g, 0);
469 c = rsa_qpubop(&rpp, MP_NEW, m);
470 c = rsa_qprivop(&rp, c, c, g);
473 die(EXIT_FAILURE, "test encryption failed");
479 /* --- Allrighty then --- */
481 kd = key_newstruct();
482 key_structsteal(kd, "n", key_newmp(KCAT_PUB, rp.n));
483 key_structsteal(kd, "e", key_newmp(KCAT_PUB, rp.e));
485 kkd = key_newstruct();
486 key_structsteal(kkd, "d", key_newmp(KCAT_PRIV | KF_BURN, rp.d));
487 key_structsteal(kkd, "p", key_newmp(KCAT_PRIV | KF_BURN, rp.p));
488 key_structsteal(kkd, "q", key_newmp(KCAT_PRIV | KF_BURN, rp.q));
489 key_structsteal(kkd, "q-inv", key_newmp(KCAT_PRIV | KF_BURN, rp.q_inv));
490 key_structsteal(kkd, "d-mod-p", key_newmp(KCAT_PRIV | KF_BURN, rp.dp));
491 key_structsteal(kkd, "d-mod-q", key_newmp(KCAT_PRIV | KF_BURN, rp.dq));
492 dolock(k, &kkd, "private");
493 key_structsteal(kd, "private", kkd);
494 key_setkeydata(k->kf, k->k, kd);
499 static void alg_dsaparam(keyopts *k)
501 static const char *pl[] = { "q", "p", "g", 0 };
502 if (!copyparam(k, pl)) {
511 /* --- Choose appropriate bit lengths if necessary --- */
518 /* --- Allocate a seed block --- */
520 sz = (k->qbits + 7) >> 3;
522 k->r->ops->fill(k->r, p, sz);
524 /* --- Allocate the parameters --- */
526 if (dsa_gen(&dp, k->qbits, k->bits, 0, p, sz, &ds,
527 (k->f & f_quiet) ? 0 : pgen_ev, 0))
528 die(EXIT_FAILURE, "DSA parameter generation failed");
530 /* --- Store the parameters --- */
532 kd = key_newstruct();
533 key_structsteal(kd, "q", key_newmp(KCAT_SHARE, dp.q));
534 key_structsteal(kd, "p", key_newmp(KCAT_SHARE, dp.p));
535 key_structsteal(kd, "g", key_newmp(KCAT_SHARE, dp.g));
539 key_setkeydata(k->kf, k->k, kd);
542 /* --- Store the seed for future verification --- */
544 c = base64_class.encoder(0, "", 0);
545 c->ops->code(c, ds.p, ds.sz, &d); c->ops->code(c, 0, 0, &d);
548 key_putattr(k->kf, k->k, "seed", d.buf);
550 dstr_putf(&d, "%u", ds.count);
551 key_putattr(k->kf, k->k, "count", d.buf);
558 static void alg_dsa(keyopts *k)
565 /* --- Get the shared parameters --- */
568 key_split(&k->k->k); kd = k->k->k;
573 /* --- Choose a private key --- */
575 x = mprand_range(MP_NEWSEC, q, k->r, 0);
576 mpmont_create(&mm, p);
577 y = mpmont_exp(&mm, MP_NEW, g, x);
579 /* --- Store everything away --- */
581 key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
583 kkd = key_newstruct();
584 key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
585 dolock(k, &kkd, "private");
586 key_structsteal(kd, "private", kkd);
588 mp_drop(x); mp_drop(y);
591 static void alg_dhparam(keyopts *k)
593 static const char *pl[] = { "p", "q", "g", 0 };
595 if (!copyparam(k, pl)) {
604 if (strcmp(k->curve, "list") == 0) {
606 LIST("Built-in prime fields", stdout, ptab[i].name, ptab[i].name);
610 if (dh_parse(&qd, &dp))
611 die(EXIT_FAILURE, "error in field spec: %s", qd.e);
613 die(EXIT_FAILURE, "junk at end of field spec");
614 if ((g = group_prime(&dp)) == 0)
615 die(EXIT_FAILURE, "invalid prime field");
616 if (!(k->f & f_quiet) && (e = G_CHECK(g, &rand_global)) != 0)
617 moan("WARNING! group check failed: %s", e);
625 /* --- Choose a large safe prime number --- */
627 if (k->f & f_limlee) {
632 rc = dh_limlee(&dp, k->qbits, k->bits,
633 (k->f & f_subgroup) ? DH_SUBGROUP : 0,
634 0, k->r, (k->f & f_quiet) ? 0 : pgen_ev, 0,
635 (k->f & f_quiet) ? 0 : pgen_evspin, 0, &nf, &f);
639 for (i = 0; i < nf; i++) {
642 mp_writedstr(f[i], &d, 10);
645 key_putattr(k->kf, k->k, "factors", d.buf);
648 } else if (k->f & f_kcdsa) {
651 rc = dh_kcdsagen(&dp, k->qbits, k->bits, 0,
652 0, k->r, (k->f & f_quiet) ? 0 : pgen_ev, 0);
657 mp_writedstr(dp.q, &d, 10);
658 mp_div(&v, 0, dp.p, dp.q);
661 mp_writedstr(v, &d, 10);
663 key_putattr(k->kf, k->k, "factors", d.buf);
667 rc = dh_gen(&dp, k->qbits, k->bits, 0, k->r,
668 (k->f & f_quiet) ? 0 : pgen_ev, 0);
671 die(EXIT_FAILURE, "Diffie-Hellman parameter generation failed");
674 kd = key_newstruct();
675 key_structsteal(kd, "p", key_newmp(KCAT_SHARE, dp.p));
676 key_structsteal(kd, "q", key_newmp(KCAT_SHARE, dp.q));
677 key_structsteal(kd, "g", key_newmp(KCAT_SHARE, dp.g));
681 key_setkeydata(k->kf, k->k, kd);
686 static void alg_dh(keyopts *k)
693 /* --- Get the shared parameters --- */
696 key_split(&k->k->k); kd = k->k->k;
701 /* --- Choose a suitable private key --- *
703 * Since %$g$% has order %$q$%, choose %$x < q$%.
706 x = mprand_range(MP_NEWSEC, q, k->r, 0);
708 /* --- Compute the public key %$y = g^x \bmod p$% --- */
710 mpmont_create(&mm, p);
711 y = mpmont_exp(&mm, MP_NEW, g, x);
714 /* --- Store everything away --- */
716 key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
718 kkd = key_newstruct();
719 key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
720 dolock(k, &kkd, "private");
721 key_structsteal(kd, "private", kkd);
723 mp_drop(x); mp_drop(y);
726 static void alg_bbs(keyopts *k)
731 /* --- Sanity checking --- */
737 /* --- Generate the BBS parameters --- */
739 if (bbs_gen(&bp, k->bits, k->r, 0,
740 (k->f & f_quiet) ? 0 : pgen_ev, 0))
741 die(EXIT_FAILURE, "Blum-Blum-Shub key generation failed");
743 /* --- Allrighty then --- */
745 kd = key_newstruct();
746 key_structsteal(kd, "n", key_newmp(KCAT_PUB, bp.n));
748 kkd = key_newstruct();
749 key_structsteal(kkd, "p", key_newmp(KCAT_PRIV | KF_BURN, bp.p));
750 key_structsteal(kkd, "q", key_newmp(KCAT_PRIV | KF_BURN, bp.q));
751 dolock(k, &kkd, "private");
752 key_structsteal(kd, "private", kkd);
753 key_setkeydata(k->kf, k->k, kd);
759 static void alg_binparam(keyopts *k)
761 static const char *pl[] = { "p", "q", "g", 0 };
762 if (!copyparam(k, pl)) {
769 /* --- Decide on a field --- */
771 if (!k->bits) k->bits = 128;
772 if (k->curve && strcmp(k->curve, "list") == 0) {
774 LIST("Built-in binary fields", stdout,
775 bintab[i].name, bintab[i].name);
779 if (k->bits <= 40) k->curve = "p1363-40";
780 else if (k->bits <= 56) k->curve = "p1363-56";
781 else if (k->bits <= 64) k->curve = "p1363-64";
782 else if (k->bits <= 80) k->curve = "p1363-80";
783 else if (k->bits <= 112) k->curve = "p1363-112";
784 else if (k->bits <= 128) k->curve = "p1363-128";
787 "no built-in binary fields provide %u-bit security",
792 /* --- Check it --- */
796 if (dhbin_parse(&qd, &gb))
797 die(EXIT_FAILURE, "error in field spec: %s", qd.e);
799 die(EXIT_FAILURE, "junk at end of field spec");
800 if ((g = group_binary(&gb)) == 0)
801 die(EXIT_FAILURE, "invalid binary field");
802 if (!(k->f & f_quiet) && (e = G_CHECK(g, &rand_global)) != 0)
803 moan("WARNING! group check failed: %s", e);
806 /* --- Write out the answer --- */
808 kd = key_newstruct();
809 key_structsteal(kd, "p", key_newmp(KCAT_SHARE, gb.p));
810 key_structsteal(kd, "q", key_newmp(KCAT_SHARE, gb.q));
811 key_structsteal(kd, "g", key_newmp(KCAT_SHARE, gb.g));
815 key_setkeydata(k->kf, k->k, kd);
820 static void alg_bin(keyopts *k)
827 /* --- Get the shared parameters --- */
830 key_split(&k->k->k); kd = k->k->k;
835 /* --- Choose a suitable private key --- *
837 * Since %$g$% has order %$q$%, choose %$x < q$%.
840 x = mprand_range(MP_NEWSEC, q, k->r, 0);
842 /* --- Compute the public key %$y = g^x \bmod p$% --- */
844 gfreduce_create(&r, p);
845 y = gfreduce_exp(&r, MP_NEW, g, x);
846 gfreduce_destroy(&r);
848 /* --- Store everything away --- */
850 key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
852 kkd = key_newstruct();
853 key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
854 dolock(k, &kkd, "private");
855 key_structsteal(kd, "private", kkd);
857 mp_drop(x); mp_drop(y);
860 static void alg_ecparam(keyopts *k)
862 static const char *pl[] = { "curve", 0 };
863 if (!copyparam(k, pl)) {
868 /* --- Decide on a curve --- */
870 if (!k->bits) k->bits = 256;
871 if (k->curve && strcmp(k->curve, "list") == 0) {
873 LIST("Built-in elliptic curves", stdout,
874 ectab[i].name, ectab[i].name);
878 if (k->bits <= 56) k->curve = "secp112r1";
879 else if (k->bits <= 64) k->curve = "secp128r1";
880 else if (k->bits <= 80) k->curve = "secp160r1";
881 else if (k->bits <= 96) k->curve = "secp192r1";
882 else if (k->bits <= 112) k->curve = "secp224r1";
883 else if (k->bits <= 128) k->curve = "secp256r1";
884 else if (k->bits <= 192) k->curve = "secp384r1";
885 else if (k->bits <= 256) k->curve = "secp521r1";
887 die(EXIT_FAILURE, "no built-in curves provide %u-bit security",
891 /* --- Check it --- */
893 if ((e = ec_getinfo(&ei, k->curve)) != 0)
894 die(EXIT_FAILURE, "error in curve spec: %s", e);
895 if (!(k->f & f_quiet) && (e = ec_checkinfo(&ei, k->r)) != 0)
896 moan("WARNING! curve check failed: %s", e);
899 /* --- Write out the answer --- */
901 kd = key_newstruct();
902 key_structsteal(kd, "curve", key_newstring(KCAT_SHARE, k->curve));
903 key_setkeydata(k->kf, k->k, kd);
908 static void alg_ec(keyopts *k)
917 /* --- Get the curve --- */
920 key_split(&k->k->k); kd = k->k->k;
921 if ((kkd = key_structfind(kd, "curve")) == 0)
922 die(EXIT_FAILURE, "unexpected failure looking up subkey `curve')");
923 if ((kkd->e & KF_ENCMASK) != KENC_STRING)
924 die(EXIT_FAILURE, "subkey `curve' is not a string");
925 if ((e = ec_getinfo(&ei, kkd->u.p)) != 0)
926 die(EXIT_FAILURE, "error in curve spec: %s", e);
928 /* --- Invent a private exponent and compute the public key --- */
930 x = mprand_range(MP_NEWSEC, ei.r, k->r, 0);
931 ec_mul(ei.c, &p, &ei.g, x);
933 /* --- Store everything away --- */
935 key_structsteal(kd, "p", key_newec(KCAT_PUB, &p));
937 kkd = key_newstruct();
938 key_structsteal(kkd, "x", key_newmp(KCAT_PRIV | KF_BURN, x));
939 dolock(k, &kkd, "private");
940 key_structsteal(kd, "private", kkd);
948 static void alg_x25519(keyopts *k)
951 octet priv[X25519_KEYSZ], pub[X25519_PUBSZ];
954 k->r->ops->fill(k->r, priv, sizeof(priv));
955 x25519(pub, priv, x25519_base);
956 kkd = key_newstruct();
957 key_structsteal(kkd, "priv",
958 key_newbinary(KCAT_PRIV | KF_BURN, priv, sizeof(priv)));
959 kd = key_newstruct();
960 key_structsteal(kd, "private", kkd);
961 key_structsteal(kd, "pub", key_newbinary(KCAT_PUB, pub, sizeof(pub)));
963 key_setkeydata(k->kf, k->k, kd);
966 static void alg_x448(keyopts *k)
969 octet priv[X448_KEYSZ], pub[X448_PUBSZ];
972 k->r->ops->fill(k->r, priv, sizeof(priv));
973 x448(pub, priv, x448_base);
974 kkd = key_newstruct();
975 key_structsteal(kkd, "priv",
976 key_newbinary(KCAT_PRIV | KF_BURN, priv, sizeof(priv)));
977 kd = key_newstruct();
978 key_structsteal(kd, "private", kkd);
979 key_structsteal(kd, "pub", key_newbinary(KCAT_PUB, pub, sizeof(pub)));
981 key_setkeydata(k->kf, k->k, kd);
984 static void alg_ed25519(keyopts *k)
987 octet priv[ED25519_KEYSZ], pub[ED25519_PUBSZ];
990 k->r->ops->fill(k->r, priv, sizeof(priv));
991 ed25519_pubkey(pub, priv, sizeof(priv));
992 kkd = key_newstruct();
993 key_structsteal(kkd, "priv",
994 key_newbinary(KCAT_PRIV | KF_BURN, priv, sizeof(priv)));
995 kd = key_newstruct();
996 key_structsteal(kd, "private", kkd);
997 key_structsteal(kd, "pub", key_newbinary(KCAT_PUB, pub, sizeof(pub)));
999 key_setkeydata(k->kf, k->k, kd);
1002 /* --- The algorithm tables --- */
1004 typedef struct keyalg {
1006 void (*proc)(keyopts *o);
1010 static 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" },
1014 { "bbs", alg_bbs, "Blum-Blum-Shub generator" },
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" },
1019 { "bindh", alg_bin, "DH over a binary field" },
1020 { "bindh-param", alg_binparam, "Binary-field DH parameters" },
1021 { "ec-param", alg_ecparam, "Elliptic curve parameters" },
1022 { "ec", alg_ec, "Elliptic curve crypto" },
1023 { "x25519", alg_x25519, "X25519 key exchange" },
1024 { "x448", alg_x448, "X448 key exchange" },
1025 { "ed25519", alg_ed25519, "Ed25519 digital signatures" },
1026 { "empty", alg_empty, "Empty parametrs-only key" },
1030 /* --- @cmd_add@ --- */
1032 static int cmd_add(int argc, char *argv[])
1035 time_t exp = KEXP_EXPIRE;
1036 uint32 kid = rand_global.ops->word(&rand_global);
1037 const char *tag = 0, *ptag = 0;
1039 keyalg *alg = algtab;
1040 const char *rtag = 0;
1041 const struct seedalg *sa = SEEDALG_DEFAULT;
1042 keyopts k = { 0, 0, DSTR_INIT, 0, 0, 0, 0, 0, 0 };
1043 const char *seed = 0;
1046 /* --- Parse options for the subcommand --- */
1049 static struct option opt[] = {
1050 { "algorithm", OPTF_ARGREQ, 0, 'a' },
1051 { "bits", OPTF_ARGREQ, 0, 'b' },
1052 { "qbits", OPTF_ARGREQ, 0, 'B' },
1053 { "parameters", OPTF_ARGREQ, 0, 'p' },
1054 { "expire", OPTF_ARGREQ, 0, 'e' },
1055 { "comment", OPTF_ARGREQ, 0, 'c' },
1056 { "tag", OPTF_ARGREQ, 0, 't' },
1057 { "rand-id", OPTF_ARGREQ, 0, 'R' },
1058 { "key-id", OPTF_ARGREQ, 0, 'I' },
1059 { "curve", OPTF_ARGREQ, 0, 'C' },
1060 { "seedalg", OPTF_ARGREQ, 0, 'A' },
1061 { "seed", OPTF_ARGREQ, 0, 's' },
1062 { "newseed", OPTF_ARGREQ, 0, 'n' },
1063 { "public-exponent", OPTF_ARGREQ, 0, 'E' },
1064 { "lock", 0, 0, 'l' },
1065 { "quiet", 0, 0, 'q' },
1066 { "lim-lee", 0, 0, 'L' },
1067 { "subgroup", 0, 0, 'S' },
1068 { "kcdsa", 0, 0, 'K' },
1071 int i = mdwopt(argc, argv, "+a:b:B:p:e:c:t:R:I:C:A:s:n:E:lqrLKS",
1076 /* --- Handle the various options --- */
1080 /* --- Read an algorithm name --- */
1084 size_t sz = strlen(optarg);
1086 if (strcmp(optarg, "list") == 0) {
1087 for (a = algtab; a->name; a++)
1088 printf("%-10s %s\n", a->name, a->help);
1093 for (a = algtab; a->name; a++) {
1094 if (strncmp(optarg, a->name, sz) == 0) {
1095 if (a->name[sz] == 0) {
1099 die(EXIT_FAILURE, "ambiguous algorithm name `%s'", optarg);
1105 die(EXIT_FAILURE, "unknown algorithm name `%s'", optarg);
1108 /* --- Bits must be nonzero and a multiple of 8 --- */
1112 k.bits = strtoul(optarg, &p, 0);
1113 if (k.bits == 0 || *p != 0)
1114 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1119 k.qbits = strtoul(optarg, &p, 0);
1120 if (k.qbits == 0 || *p != 0)
1121 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1124 /* --- Parameter selection --- */
1130 /* --- Expiry dates get passed to @get_date@ for parsing --- */
1133 if (strcmp(optarg, "forever") == 0)
1136 exp = get_date(optarg, 0);
1138 die(EXIT_FAILURE, "bad expiry date `%s'", optarg);
1142 /* --- Store comments without interpretation --- */
1145 if (key_chkcomment(optarg))
1146 die(EXIT_FAILURE, "bad comment string `%s'", optarg);
1150 /* --- Elliptic curve parameters --- */
1156 /* --- Store tags --- */
1159 if (key_chkident(optarg))
1160 die(EXIT_FAILURE, "bad tag string `%s'", optarg);
1167 /* --- Seeding --- */
1170 const struct seedalg *ss;
1171 if (strcmp(optarg, "list") == 0) {
1172 printf("Seed algorithms:\n");
1173 for (ss = seedtab; ss->p; ss++)
1174 printf(" %s\n", ss->p);
1177 if (seed) die(EXIT_FAILURE, "seed already set -- put -A first");
1179 for (ss = seedtab; ss->p; ss++) {
1180 if (strcmp(optarg, ss->p) == 0)
1184 die(EXIT_FAILURE, "seed algorithm `%s' not known", optarg);
1191 if (seed) die(EXIT_FAILURE, "seed already set");
1192 c = base64_class.decoder(CDCF_IGNEQPAD);
1193 if ((rc = c->ops->code(c, optarg, strlen(optarg), &d)) != 0 ||
1194 (rc = c->ops->code(c, 0, 0, &d)) != 0)
1195 die(EXIT_FAILURE, "invalid seed base64: %s", codec_strerror(rc));
1197 k.r = sa->gen(d.buf, d.len);
1206 unsigned n = strtoul(optarg, &p, 0);
1207 if (n == 0 || *p != 0 || n % 8 != 0)
1208 die(EXIT_FAILURE, "bad seed length `%s'", optarg);
1209 if (seed) die(EXIT_FAILURE, "seed already set");
1212 rand_get(RAND_GLOBAL, p, n);
1213 c = base64_class.encoder(0, "", 0);
1214 c->ops->code(c, p, n, &d); c->ops->code(c, 0, 0, &d);
1217 k.r = sa->gen(p, n);
1220 /* --- Key id --- */
1227 id = strtoul(optarg, &p, 16);
1228 if (errno || *p || id > MASK32)
1229 die(EXIT_FAILURE, "bad key-id `%s'", optarg);
1233 /* --- Public exponent --- */
1237 k.e = mp_readstring(k.e, optarg, &p, 0);
1238 if (!k.e || *p || MP_CMP(k.e, <, MP_THREE) || MP_EVENP(k.e))
1239 die(EXIT_FAILURE, "bad exponent `%s'", optarg);
1242 /* --- Other flags --- */
1263 /* --- Other things are bogus --- */
1271 /* --- Various sorts of bogosity --- */
1273 if ((k.f & f_bogus) || optind + 1 > argc) {
1275 "Usage: add [OPTIONS] TYPE [ATTR...]");
1277 if (key_chkident(argv[optind]))
1278 die(EXIT_FAILURE, "bad key type `%s'", argv[optind]);
1280 /* --- Set up various bits of the state --- */
1282 if (exp == KEXP_EXPIRE)
1283 exp = time(0) + 14 * 24 * 60 * 60;
1285 /* --- Open the file and create the basic key block --- *
1287 * Keep on generating keyids until one of them doesn't collide.
1290 doopen(&f, KOPEN_WRITE);
1293 /* --- Key the generator --- */
1299 if ((err = key_new(&f, kid, argv[optind], exp, &k.k)) == 0)
1301 else if (err != KERR_DUPID)
1302 die(EXIT_FAILURE, "error adding new key: %s", key_strerror(err));
1305 /* --- Set various simple attributes --- */
1310 if (k.f & f_retag) {
1311 if ((kk = key_bytag(&f, tag)) != 0 &&
1313 strcmp(kk->tag, tag) == 0)
1314 key_settag(&f, kk, 0);
1316 if ((err = key_settag(&f, k.k, tag)) != 0)
1317 die(EXIT_FAILURE, "error setting key tag: %s", key_strerror(err));
1321 int err = key_setcomment(&f, k.k, c);
1323 die(EXIT_FAILURE, "error setting key comment: %s", key_strerror(err));
1326 setattr(&f, k.k, argv + optind + 1);
1328 key_putattr(&f, k.k, "genseed", seed);
1329 key_putattr(&f, k.k, "seedalg", sa->p);
1332 key_fulltag(k.k, &k.tag);
1334 /* --- Find the parameter key --- */
1336 if (ptag && (k.p = key_bytag(&f, ptag)) == 0)
1337 die(EXIT_FAILURE, "parameter key `%s' not found", ptag);
1339 /* --- Now generate the actual key data --- */
1345 dstr_destroy(&k.tag);
1350 /*----- Key listing -------------------------------------------------------*/
1352 /* --- Listing options --- */
1354 typedef struct listopts {
1355 const char *tfmt; /* Date format (@strftime@-style) */
1356 int v; /* Verbosity level */
1357 unsigned f; /* Various flags */
1358 time_t t; /* Time now (for key expiry) */
1359 key_filter kf; /* Filter for matching keys */
1362 /* --- Listing flags --- */
1364 #define f_newline 2u /* Write newline before next entry */
1365 #define f_attr 4u /* Written at least one attribute */
1366 #define f_utc 8u /* Emit UTC time, not local time */
1368 /* --- @showkeydata@ --- *
1370 * Arguments: @key_data *k@ = pointer to key to write
1371 * @int ind@ = indentation level
1372 * @listopts *o@ = listing options
1373 * @dstr *d@ = tag string for this subkey
1377 * Use: Emits a piece of key data in a human-readable format.
1380 static void showkeydata(key_data *k, int ind, listopts *o, dstr *d)
1382 #define INDENT(i) do { \
1384 for (_i = 0; _i < (i); _i++) { \
1389 switch (k->e & KF_ENCMASK) {
1391 /* --- Binary key data --- *
1393 * Emit as a simple hex dump.
1397 const octet *p = k->u.k.k;
1398 const octet *l = p + k->u.k.sz;
1401 fputs(" {", stdout);
1406 } else if (sz % 8 == 0)
1410 printf("%02x", *p++);
1415 fputs("}\n", stdout);
1418 /* --- Encrypted data --- *
1420 * If the user is sufficiently keen, ask for a passphrase and decrypt the
1421 * key. Otherwise just say that it's encrypted and move on.
1426 fputs(" encrypted\n", stdout);
1429 if (key_punlock(&kd, k, d->buf))
1430 printf(" <failed to unlock %s>\n", d->buf);
1432 fputs(" encrypted", stdout);
1433 showkeydata(kd, ind, o, d);
1439 /* --- Integer keys --- *
1441 * Emit as a large integer in decimal. This makes using the key in
1442 * `calc' or whatever easier.
1447 mp_writefile(k->u.m, stdout, 10);
1451 /* --- Strings --- */
1454 printf(" `%s'\n", k->u.p);
1457 /* --- Elliptic curve points --- */
1460 if (EC_ATINF(&k->u.e))
1461 fputs(" inf\n", stdout);
1463 fputs(" 0x", stdout); mp_writefile(k->u.e.x, stdout, 16);
1464 fputs(", 0x", stdout); mp_writefile(k->u.e.y, stdout, 16);
1469 /* --- Structured keys --- *
1471 * Just iterate over the subkeys.
1479 fputs(" {\n", stdout);
1480 for (key_mksubkeyiter(&i, k); key_nextsubkey(&i, &tag, &k); ) {
1481 if (!key_match(k, &o->kf))
1484 printf("%s =", tag);
1486 dstr_putf(d, ".%s", tag);
1487 showkeydata(k, ind + 2, o, d);
1490 fputs("}\n", stdout);
1497 /* --- @showkey@ --- *
1499 * Arguments: @key *k@ = pointer to key to show
1500 * @listopts *o@ = pointer to listing options
1504 * Use: Emits a listing of a particular key.
1507 static void showkey(key *k, listopts *o)
1509 char ebuf[24], dbuf[24];
1512 /* --- Skip the key if the filter doesn't match --- */
1514 if (!key_match(k->k, &o->kf))
1517 /* --- Sort out the expiry and deletion times --- */
1519 if (KEY_EXPIRED(o->t, k->exp))
1520 strcpy(ebuf, "expired");
1521 else if (k->exp == KEXP_FOREVER)
1522 strcpy(ebuf, "forever");
1524 tm = (o->f & f_utc) ? gmtime(&k->exp) : localtime(&k->exp);
1525 strftime(ebuf, sizeof(ebuf), o->tfmt, tm);
1528 if (KEY_EXPIRED(o->t, k->del))
1529 strcpy(dbuf, "deleted");
1530 else if (k->del == KEXP_FOREVER)
1531 strcpy(dbuf, "forever");
1533 tm = (o->f & f_utc) ? gmtime(&k->del) : localtime(&k->del);
1534 strftime(dbuf, sizeof(dbuf), o->tfmt, tm);
1537 /* --- If in compact format, just display and quit --- */
1540 if (!(o->f & f_newline)) {
1541 printf("%8s %-20s %-20s %-10s %s\n",
1542 "Id", "Tag", "Type", "Expire", "Delete");
1544 printf("%08lx %-20s %-20s %-10s %s\n",
1545 (unsigned long)k->id, k->tag ? k->tag : "<none>",
1546 k->type, ebuf, dbuf);
1551 /* --- Display the standard header --- */
1553 if (o->f & f_newline)
1554 fputc('\n', stdout);
1555 printf("keyid: %08lx\n", (unsigned long)k->id);
1556 printf("tag: %s\n", k->tag ? k->tag : "<none>");
1557 printf("type: %s\n", k->type);
1558 printf("expiry: %s\n", ebuf);
1559 printf("delete: %s\n", dbuf);
1560 printf("comment: %s\n", k->c ? k->c : "<none>");
1562 /* --- Display the attributes --- */
1566 const char *av, *an;
1569 printf("attributes:");
1570 for (key_mkattriter(&i, k); key_nextattr(&i, &an, &av); ) {
1571 printf("\n %s = %s", an, av);
1575 fputc('\n', stdout);
1580 /* --- If dumping requested, dump the raw key data --- */
1584 fputs("key:", stdout);
1586 showkeydata(k->k, 0, o, &d);
1593 /* --- @cmd_list@ --- */
1595 static int cmd_list(int argc, char *argv[])
1599 listopts o = { 0, 0, 0, 0, { 0, 0 } };
1601 /* --- Parse subcommand options --- */
1604 static struct option opt[] = {
1605 { "quiet", 0, 0, 'q' },
1606 { "verbose", 0, 0, 'v' },
1607 { "utc", 0, 0, 'u' },
1608 { "filter", OPTF_ARGREQ, 0, 'f' },
1611 int i = mdwopt(argc, argv, "+uqvf:", opt, 0, 0, 0);
1628 int e = key_readflags(optarg, &p, &o.kf.f, &o.kf.m);
1630 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1639 die(EXIT_FAILURE, "Usage: list [-uqv] [-f FILTER] [TAG...]");
1641 /* --- Open the key file --- */
1643 doopen(&f, KOPEN_READ);
1646 /* --- Set up the time format --- */
1649 o.tfmt = "%Y-%m-%d";
1650 else if (o.f & f_utc)
1651 o.tfmt = "%Y-%m-%d %H:%M:%S UTC";
1653 o.tfmt = "%Y-%m-%d %H:%M:%S %Z";
1655 /* --- If specific keys were requested use them, otherwise do all --- *
1657 * Some day, this might turn into a wildcard match.
1660 if (optind < argc) {
1662 if ((k = key_bytag(&f, argv[optind])) != 0)
1665 moan("key `%s' not found", argv[optind]);
1669 } while (optind < argc);
1672 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1680 return (EXIT_FAILURE);
1685 /*----- Command implementation --------------------------------------------*/
1687 /* --- @cmd_expire@ --- */
1689 static int cmd_expire(int argc, char *argv[])
1697 die(EXIT_FAILURE, "Usage: expire TAG...");
1698 doopen(&f, KOPEN_WRITE);
1699 for (i = 1; i < argc; i++) {
1700 if ((k = key_bytag(&f, argv[i])) != 0)
1703 moan("key `%s' not found", argv[i]);
1711 /* --- @cmd_delete@ --- */
1713 static int cmd_delete(int argc, char *argv[])
1721 die(EXIT_FAILURE, "Usage: delete TAG...");
1722 doopen(&f, KOPEN_WRITE);
1723 for (i = 1; i < argc; i++) {
1724 if ((k = key_bytag(&f, argv[i])) != 0)
1727 moan("key `%s' not found", argv[i]);
1735 /* --- @cmd_setattr@ --- */
1737 static int cmd_setattr(int argc, char *argv[])
1743 die(EXIT_FAILURE, "Usage: setattr TAG ATTR...");
1744 doopen(&f, KOPEN_WRITE);
1745 if ((k = key_bytag(&f, argv[1])) == 0)
1746 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1747 setattr(&f, k, argv + 2);
1752 /* --- @cmd_getattr@ --- */
1754 static int cmd_getattr(int argc, char *argv[])
1762 die(EXIT_FAILURE, "Usage: getattr TAG ATTR");
1763 doopen(&f, KOPEN_READ);
1764 if ((k = key_bytag(&f, argv[1])) == 0)
1765 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1767 if ((p = key_getattr(&f, k, argv[2])) == 0)
1768 die(EXIT_FAILURE, "no attribute `%s' for key `%s'", argv[2], d.buf);
1775 /* --- @cmd_finger@ --- */
1777 static const struct fpres {
1779 const codec_class *cdc;
1780 unsigned short ival;
1783 { "hex", &hex_class, 8, "-:" },
1784 { "base32", &base32_class, 6, ":" },
1788 static void fingerprint(key *k, const struct fpres *fpres,
1789 const gchash *ch, const key_filter *kf)
1792 dstr d = DSTR_INIT, dd = DSTR_INIT;
1798 if (key_fingerprint(k, h, kf)) {
1800 c = fpres->cdc->encoder(CDCF_LOWERC | CDCF_NOEQPAD, "", 0);
1801 c->ops->code(c, p, ch->hashsz, &dd); c->ops->code(c, 0, 0, &dd);
1803 for (i = 0; i < dd.len; i++) {
1804 if (i && i%fpres->ival == 0) dstr_putc(&d, fpres->sep[0]);
1805 dstr_putc(&d, dd.buf[i]);
1807 dstr_putc(&d, ' '); key_fulltag(k, &d); dstr_putc(&d, '\n');
1808 dstr_write(&d, stdout);
1810 dstr_destroy(&d); dstr_destroy(&dd);
1814 static const struct fpres *lookup_fpres(const char *name)
1816 const struct fpres *fpres;
1817 for (fpres = fprestab; fpres->name; fpres++)
1818 if (strcmp(fpres->name, name) == 0) return (fpres);
1819 die(EXIT_FAILURE, "unknown presentation syle `%s'", name);
1822 static int cmd_finger(int argc, char *argv[])
1826 const struct fpres *fpres = fprestab;
1827 const gchash *ch = &rmd160;
1828 key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1831 static struct option opt[] = {
1832 { "filter", OPTF_ARGREQ, 0, 'f' },
1833 { "presentation", OPTF_ARGREQ, 0, 'p' },
1834 { "algorithm", OPTF_ARGREQ, 0, 'a' },
1837 int i = mdwopt(argc, argv, "+f:a:p:", opt, 0, 0, 0);
1843 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1845 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1848 fpres = lookup_fpres(optarg);
1851 if ((ch = ghash_byname(optarg)) == 0)
1852 die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1860 argv += optind; argc -= optind;
1863 "Usage: fingerprint [-a HASHALG] [-p STYLE] [-f FILTER] [TAG...]");
1866 doopen(&f, KOPEN_READ);
1870 for (i = 0; i < argc; i++) {
1871 key *k = key_bytag(&f, argv[i]);
1873 fingerprint(k, fpres, ch, &kf);
1876 moan("key `%s' not found", argv[i]);
1882 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1883 fingerprint(k, fpres, ch, &kf);
1888 /* --- @cmd_verify@ --- */
1890 static int cmd_verify(int argc, char *argv[])
1894 const gchash *ch = &rmd160;
1898 dstr d = DSTR_INIT, dd = DSTR_INIT;
1901 const struct fpres *fpres = fprestab;
1902 key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1905 static struct option opt[] = {
1906 { "filter", OPTF_ARGREQ, 0, 'f' },
1907 { "presentation", OPTF_ARGREQ, 0, 'p' },
1908 { "algorithm", OPTF_ARGREQ, 0, 'a' },
1911 int i = mdwopt(argc, argv, "+f:a:p:", opt, 0, 0, 0);
1917 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1919 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1922 fpres = lookup_fpres(optarg);
1925 if ((ch = ghash_byname(optarg)) == 0)
1926 die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1934 argv += optind; argc -= optind;
1935 if (rc || argc != 2) {
1937 "Usage: verify [-a HASHALG] [-p STYLE] [-f FILTER] TAG FINGERPRINT");
1940 doopen(&f, KOPEN_READ);
1942 if ((k = key_bytag(&f, argv[0])) == 0)
1943 die(EXIT_FAILURE, "key `%s' not found", argv[0]);
1944 for (p = argv[1]; *p; p++) {
1945 if (strchr(fpres->sep, *p)) continue;
1948 c = fpres->cdc->decoder(CDCF_IGNCASE | CDCF_IGNEQPAD |
1949 CDCF_IGNSPC | CDCF_IGNNEWL);
1950 if ((rc = c->ops->code(c, dd.buf, dd.len, &d)) != 0 ||
1951 (rc = c->ops->code(c, 0, 0, &d)) != 0)
1952 die(EXIT_FAILURE, "invalid fingerprint: %s", codec_strerror(rc));
1954 if (d.len != ch->hashsz) {
1955 die(EXIT_FAILURE, "incorrect fingerprint length (%lu != %lu)",
1956 (unsigned long)d.len, (unsigned long)ch->hashsz);
1959 if (!key_fingerprint(k, h, &kf))
1960 die(EXIT_FAILURE, "key has no fingerprintable components (as filtered)");
1961 fpr = GH_DONE(h, 0);
1962 if (memcmp(fpr, d.buf, ch->hashsz) != 0)
1963 die(EXIT_FAILURE, "key fingerprint mismatch");
1964 dstr_destroy(&d); dstr_destroy(&dd);
1969 /* --- @cmd_comment@ --- */
1971 static int cmd_comment(int argc, char *argv[])
1977 if (argc < 2 || argc > 3)
1978 die(EXIT_FAILURE, "Usage: comment TAG [COMMENT]");
1979 doopen(&f, KOPEN_WRITE);
1980 if ((k = key_bytag(&f, argv[1])) == 0)
1981 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1982 if ((err = key_setcomment(&f, k, argv[2])) != 0)
1983 die(EXIT_FAILURE, "bad comment `%s': %s", argv[2], key_strerror(err));
1988 /* --- @cmd_tag@ --- */
1990 static int cmd_tag(int argc, char *argv[])
1999 static struct option opt[] = {
2000 { "retag", 0, 0, 'r' },
2003 int i = mdwopt(argc, argv, "+r", opt, 0, 0, 0);
2016 argv += optind; argc -= optind;
2017 if (argc < 1 || argc > 2 || rc)
2018 die(EXIT_FAILURE, "Usage: tag [-r] TAG [NEW-TAG]");
2019 doopen(&f, KOPEN_WRITE);
2020 if (flags & f_retag) {
2021 if ((k = key_bytag(&f, argv[1])) != 0 && strcmp(k->tag, argv[1]) == 0)
2022 key_settag(&f, k, 0);
2024 if ((k = key_bytag(&f, argv[0])) == 0)
2025 die(EXIT_FAILURE, "key `%s' not found", argv[0]);
2026 if ((err = key_settag(&f, k, argv[1])) != 0)
2027 die(EXIT_FAILURE, "bad tag `%s': %s", argv[1], key_strerror(err));
2032 /* --- @cmd_lock@ --- */
2034 static int cmd_lock(int argc, char *argv[])
2042 die(EXIT_FAILURE, "Usage: lock QTAG");
2043 doopen(&f, KOPEN_WRITE);
2044 if (key_qtag(&f, argv[1], &d, &k, &kd))
2045 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
2046 if ((*kd)->e == KENC_ENCRYPT && key_punlock(kd, 0, d.buf))
2047 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
2048 if (key_plock(kd, 0, d.buf))
2049 die(EXIT_FAILURE, "failed to lock key `%s'", d.buf);
2055 /* --- @cmd_unlock@ --- */
2057 static int cmd_unlock(int argc, char *argv[])
2065 die(EXIT_FAILURE, "Usage: unlock QTAG");
2066 doopen(&f, KOPEN_WRITE);
2067 if (key_qtag(&f, argv[1], &d, &k, &kd))
2068 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
2069 if ((*kd)->e != KENC_ENCRYPT)
2070 die(EXIT_FAILURE, "key `%s' is not encrypted", d.buf);
2071 if (key_punlock(kd, 0, d.buf))
2072 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
2078 /* --- @cmd_extract@ --- */
2080 static int cmd_extract(int argc, char *argv[])
2086 key_filter kf = { 0, 0 };
2088 const char *outfile = 0;
2092 static struct option opt[] = {
2093 { "filter", OPTF_ARGREQ, 0, 'f' },
2096 int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
2102 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
2104 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
2112 argv += optind; argc -= optind;
2114 die(EXIT_FAILURE, "Usage: extract [-f FILTER] FILE [TAG...]");
2115 if (strcmp(*argv, "-") == 0)
2119 dstr_putf(&d, "%s.new", outfile);
2120 if (!(fp = fopen(d.buf, "w"))) {
2121 die(EXIT_FAILURE, "couldn't open `%s' for writing: %s",
2122 d.buf, strerror(errno));
2126 doopen(&f, KOPEN_READ);
2130 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
2131 key_extract(&f, k, fp, &kf);
2133 for (i = 1; i < argc; i++) {
2134 if ((k = key_bytag(&f, argv[i])) != 0)
2135 key_extract(&f, k, fp, &kf);
2137 moan("key `%s' not found", argv[i]);
2142 if (fclose(fp) || (outfile && rename(d.buf, outfile)))
2143 die(EXIT_FAILURE, "error writing file: %s", strerror(errno));
2149 /* --- @cmd_tidy@ --- */
2151 static int cmd_tidy(int argc, char *argv[])
2155 die(EXIT_FAILURE, "Usage: tidy");
2156 doopen(&f, KOPEN_WRITE);
2157 f.f |= KF_MODIFIED; /* Nasty hack */
2162 /* --- @cmd_merge@ --- */
2164 static int cmd_merge(int argc, char *argv[])
2170 die(EXIT_FAILURE, "Usage: merge FILE");
2171 if (strcmp(argv[1], "-") == 0)
2173 else if (!(fp = fopen(argv[1], "r"))) {
2174 die(EXIT_FAILURE, "couldn't open `%s' for reading: %s",
2175 argv[1], strerror(errno));
2178 doopen(&f, KOPEN_WRITE);
2179 key_merge(&f, argv[1], fp, key_moan, 0);
2184 /* --- @cmd_show@ --- */
2188 listtab[i].name, listtab[i].name) \
2189 LI("Hash functions", hash, \
2190 ghashtab[i], ghashtab[i]->name) \
2191 LI("Elliptic curves", ec, \
2192 ectab[i].name, ectab[i].name) \
2193 LI("Prime Diffie-Hellman groups", dh, \
2194 ptab[i].name, ptab[i].name) \
2195 LI("Binary Diffie-Hellman groups", bindh, \
2196 bintab[i].name, bintab[i].name) \
2197 LI("Key-generation algorithms", keygen, \
2198 algtab[i].name, algtab[i].name) \
2199 LI("Random seeding algorithms", seed, \
2200 seedtab[i].p, seedtab[i].p) \
2201 LI("Fingerprint presentation styles", fpres, \
2202 fprestab[i].name, fprestab[i].name)
2204 MAKELISTTAB(listtab, LISTS)
2206 static int cmd_show(int argc, char *argv[])
2208 return (displaylists(listtab, argv + 1));
2211 /*----- Main command table ------------------------------------------------*/
2213 static int cmd_help(int argc, char *argv[]);
2215 static cmd cmds[] = {
2216 { "help", cmd_help, "help [COMMAND...]" },
2217 { "show", cmd_show, "show [ITEM...]" },
2218 { "list", cmd_list, "list [-uqv] [-f FILTER] [TAG...]", "\
2221 -u, --utc Display expiry times etc. in UTC, not local time.\n\
2222 -q, --quiet Show less information.\n\
2223 -v, --verbose Show more information.\n\
2225 { "fingerprint", cmd_finger,
2226 "fingerprint [-a HASHALG] [-p STYLE] [-f FILTER] [TAG...]", "\
2229 -f, --filter=FILT Only hash key components matching FILT.\n\
2230 -p, --presentation=STYLE Use STYLE for presenting fingerprints.\n\
2231 -a, --algorithm=HASH Use the named HASH algorithm.\n\
2232 ($ show hash for list.)\n\
2234 { "verify", cmd_verify,
2235 "verify [-a HASH] [-p STYLE] [-f FILTER] TAG FINGERPRINT", "\
2238 -f, --filter=FILT Only hash key components matching FILT.\n\
2239 -p, --presentation=STYLE Expect FINGERPRINT in the given STYLE.\n\
2240 -a, --algorithm=HASH Use the named HASH algorithm.\n\
2241 ($ show hash for list.)\n\
2243 { "extract", cmd_extract, "extract [-f FILTER] FILE [TAG...]", "\
2246 -f, --filter=FILT Only extract key components matching FILT.\n\
2248 { "merge", cmd_merge, "merge FILE" },
2249 { "expire", cmd_expire, "expire TAG..." },
2250 { "delete", cmd_delete, "delete TAG..." },
2251 { "setattr", cmd_setattr, "setattr TAG ATTR..." },
2252 { "getattr", cmd_getattr, "getattr TAG ATTR" },
2253 { "comment", cmd_comment, "comment TAG [COMMENT]" },
2254 { "lock", cmd_lock, "lock QTAG" },
2255 { "unlock", cmd_unlock, "unlock QTAG" },
2256 { "tag", cmd_tag, "tag [-r] TAG [NEW-TAG]", "\
2259 -r, --retag Untag any key currently called new-tag.\n\
2261 { "tidy", cmd_tidy, "tidy" },
2263 "add [-OPTIONS] TYPE [ATTR...]\n\
2264 Options: [-lqrLKS] [-a ALG] [-bB BITS] [-p PARAM] [-R TAG]\n\
2265 [-A SEEDALG] [-s SEED] [-n BITS] [-I KEYID]\n\
2266 [-e EXPIRE] [-t TAG] [-c COMMENT]", "\
2269 -a, --algorithm=ALG Generate keys suitable for ALG.\n\
2270 ($ show keygen for list.)\n\
2271 -b, --bits=N Generate an N-bit key.\n\
2272 -B, --qbits=N Use an N-bit subgroup or factors.\n\
2273 -p, --parameters=TAG Get group parameters from TAG.\n\
2274 -C, --curve=NAME Use elliptic curve or DH group NAME.\n\
2275 ($ show ec or $ show dh for list.)\n\
2276 -A, --seedalg=ALG Use pseudorandom generator ALG to generate key.\n\
2277 ($ show seed for list.)\n\
2278 -s, --seed=BASE64 Use Base64-encoded string BASE64 as seed.\n\
2279 -n, --newseed=COUNT Generate new COUNT-bit seed.\n\
2280 -e, --expire=TIME Make the key expire after TIME.\n\
2281 -c, --comment=STRING Attach the command STRING to the key.\n\
2282 -t, --tag=TAG Tag the key with the name TAG.\n\
2283 -r, --retag Untag any key currently with that tag.\n\
2284 -R, --rand-id=TAG Use key named TAG for the random number generator.\n\
2285 -I, --key-id=ID Force the key-id for the new key.\n\
2286 -l, --lock Lock the generated key with a passphrase.\n\
2287 -q, --quiet Don't give progress indicators while working.\n\
2288 -L, --lim-lee Generate Lim-Lee primes for Diffie-Hellman groups.\n\
2289 -K, --kcdsa Generate KCDSA-style Lim-Lee primes for DH groups.\n\
2290 -S, --subgroup Use a prime-order subgroup for Diffie-Hellman.\n\
2295 static int cmd_help(int argc, char *argv[])
2297 sc_help(cmds, stdout, argv + 1);
2301 /*----- Main code ---------------------------------------------------------*/
2303 /* --- Helpful GNUy functions --- */
2305 static void usage(FILE *fp)
2307 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
2310 void version(FILE *fp)
2312 pquis(fp, "$, Catacomb version " VERSION "\n");
2315 void help_global(FILE *fp)
2319 Performs various simple key management operations.\n\
2321 Global command line options:\n\
2323 -h, --help [COMMAND...] Display this help text (or help for COMMANDs).\n\
2324 -v, --version Display version number.\n\
2325 -u, --usage Display short usage summary.\n\
2327 -k, --keyring=FILE Read and write keys in FILE.\n",
2333 * Arguments: @int argc@ = number of command line arguments
2334 * @char *argv[]@ = array of command line arguments
2336 * Returns: Nonzero on failure.
2338 * Use: Main program. Performs simple key management functions.
2341 int main(int argc, char *argv[])
2347 /* --- Initialization --- */
2352 /* --- Parse command line options --- */
2355 static struct option opt[] = {
2357 /* --- Standard GNUy help options --- */
2359 { "help", 0, 0, 'h' },
2360 { "version", 0, 0, 'v' },
2361 { "usage", 0, 0, 'u' },
2363 /* --- Real live useful options --- */
2365 { "keyring", OPTF_ARGREQ, 0, 'k' },
2367 /* --- Magic terminator --- */
2371 int i = mdwopt(argc, argv, "+hvu k:", opt, 0, 0, 0);
2377 /* --- GNU help options --- */
2380 sc_help(cmds, stdout, argv + optind);
2389 /* --- Real useful options --- */
2395 /* --- Bogosity --- */
2403 /* --- Complain about excessive bogons --- */
2405 if (f & f_bogus || optind == argc) {
2410 /* --- Initialize the Catacomb random number generator --- */
2412 rand_noisesrc(RAND_GLOBAL, &noise_source);
2413 rand_seed(RAND_GLOBAL, 160);
2415 /* --- Dispatch to appropriate command handler --- */
2420 return (findcmd(cmds, argv[0])->cmd(argc, argv));
2423 /*----- That's all, folks -------------------------------------------------*/