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/macros.h>
46 #include <mLib/mdwopt.h>
47 #include <mLib/quis.h>
48 #include <mLib/report.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"
94 /*----- Handy global state ------------------------------------------------*/
96 static const char *keyfile = "keyring";
98 /*----- Useful shared functions -------------------------------------------*/
100 /* --- @doopen@ --- *
102 * Arguments: @key_file *f@ = pointer to key file block
103 * @unsigned how@ = method to open file with
107 * Use: Opens a key file and handles errors by panicking
111 static void doopen(key_file *f, unsigned how)
113 if (key_open(f, keyfile, how, key_moan, 0)){
114 die(EXIT_FAILURE, "couldn't open keyring `%s': %s",
115 keyfile, strerror(errno));
119 /* --- @doclose@ --- *
121 * Arguments: @key_file *f@ = pointer to key file block
125 * Use: Closes a key file and handles errors by panicking
129 static void doclose(key_file *f)
131 switch (key_close(f)) {
133 die(EXIT_FAILURE, "couldn't write file `%s': %s",
134 keyfile, strerror(errno));
136 die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
137 keyfile, strerror(errno));
141 /* --- @setattr@ --- *
143 * Arguments: @key_file *f@ = pointer to key file block
144 * @key *k@ = pointer to key block
145 * @char *v[]@ = array of assignments (overwritten!)
149 * Use: Applies the attribute assignments to the key.
152 static void setattr(key_file *f, key *k, char *v[])
157 size_t eq = strcspn(p, "=");
159 moan("invalid assignment: `%s' (ignored)", p);
165 if ((err = key_putattr(f, k, *v, *p ? p : 0)) != 0)
166 die(EXIT_FAILURE, "couldn't set attributes: %s", key_strerror(err));
171 /*----- Seeding -----------------------------------------------------------*/
173 const struct seedalg { const char *p; grand *(*gen)(const void *, size_t); }
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 },
189 #define SEEDALG_DEFAULT (seedtab + 2)
191 /*----- Key generation ----------------------------------------------------*/
193 /* --- Key generation parameters --- */
195 typedef 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 */
201 const char *curve; /* Elliptic curve name/info */
202 grand *r; /* Random number source */
203 mp *e; /* Public exponent */
204 key *p; /* Parameters key-data */
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 */
212 #define f_retag 32u /* Remove any existing tag */
213 #define f_kcdsa 64u /* Generate KCDSA primes */
215 /* --- @dolock@ --- *
217 * Arguments: @keyopts *k@ = key generation options
218 * @key_data **kd@ = pointer to key data to lock
219 * @const char *t@ = tag suffix or null
223 * Use: Does passphrase locking on new keys.
226 static void dolock(keyopts *k, key_data **kd, const char *t)
228 if (!(k->f & f_lock))
231 dstr_putf(&k->tag, ".%s", t);
232 if (key_plock(kd, 0, k->tag.buf))
233 die(EXIT_FAILURE, "couldn't lock key");
236 /* --- @copyparam@ --- *
238 * Arguments: @keyopts *k@ = pointer to key options
239 * @const char **pp@ = checklist of parameters, or null
241 * Returns: Nonzero if parameters copied; zero if you have to generate
244 * Use: Copies parameters from a source key to the current one.
247 static int copyparam(keyopts *k, const char **pp)
258 /* --- Quick check if no parameters supplied --- */
263 /* --- Copy the key data if there's anything we want --- */
267 /* --- Run through the checklist --- */
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);
273 key_data *kd = key_structfind(k->p->k, *pp);
276 "bad parameter key `%s': parameter `%s' not found", t.buf, *pp);
278 if (!KEY_MATCH(kd, &kf)) {
280 "bad parameter key `%s': subkey `%s' is not shared", t.buf, *pp);
285 /* --- Copy over the parameters --- */
287 kd = key_copydata(k->p->k, &kf);
289 key_setkeydata(k->kf, k->k, kd);
293 /* --- Copy over attributes --- */
295 for (key_mkattriter(&i, k->p); key_nextattr(&i, &n, &v); )
296 key_putattr(k->kf, k->k, n, v);
306 * Arguments: @key_data *k@ = pointer to key data block
307 * @const char *tag@ = tag string to use
309 * Returns: Pointer to multiprecision integer key item.
311 * Use: Fetches an MP key component.
314 static mp *getmp(key_data *k, const char *tag)
316 k = key_structfind(k, tag);
318 die(EXIT_FAILURE, "unexpected failure looking up subkey `%s'", tag);
319 if ((k->e & KF_ENCMASK) != KENC_MP)
320 die(EXIT_FAILURE, "subkey `%s' has an incompatible type", tag);
324 /* --- @keyrand@ --- *
326 * Arguments: @key_file *kf@ = pointer to key file
327 * @const char *id@ = pointer to key id (or null)
331 * Use: Keys the random number generator.
334 static void keyrand(key_file *kf, const char *id)
338 /* --- Find the key --- */
341 if ((k = key_bytag(kf, id)) == 0)
342 die(EXIT_FAILURE, "key `%s' not found", id);
344 k = key_bytype(kf, "catacomb-rand");
347 key_data *kd = k->k, *kkd;
351 switch (kd->e & KF_ENCMASK) {
357 if (key_punlock(&kkd, kd, d.buf))
358 die(EXIT_FAILURE, "error unlocking key `%s'", d.buf);
366 die(EXIT_FAILURE, "bad encoding type for key `%s'", d.buf);
370 /* --- Key the generator --- */
372 rand_key(RAND_GLOBAL, kd->u.k.k, kd->u.k.sz);
377 /* --- Key generation algorithms --- */
379 static void alg_empty(keyopts *k)
382 key_setkeydata(k->kf, k->k,
383 key_newstring(KCAT_SHARE, k->curve ? k->curve : "."));
386 static void alg_binary(keyopts *k)
397 sz = (k->bits + 7) >> 3;
399 m = (1 << (((k->bits - 1) & 7) + 1)) - 1;
400 k->r->ops->fill(k->r, p, sz);
402 kd = key_newbinary(KCAT_SYMM | KF_BURN, p, sz);
405 key_setkeydata(k->kf, k->k, kd);
410 static void alg_des(keyopts *k)
419 if (k->bits % 56 || k->bits > 168)
420 die(EXIT_FAILURE, "DES keys must be 56, 112 or 168 bits long");
424 k->r->ops->fill(k->r, p, sz);
425 des_fixparity(p, p, sz);
426 kd = key_newbinary(KCAT_SYMM | KF_BURN, p, sz);
429 key_setkeydata(k->kf, k->k, kd);
434 static void alg_rsa(keyopts *k)
439 /* --- Sanity checking --- */
445 die(EXIT_FAILURE, "RSA key too tiny");
447 k->e = mp_fromulong(MP_NEW, 65537);
449 /* --- Generate the RSA parameters --- */
451 if (rsa_gen_e(&rp, k->bits, k->e, k->r, 0,
452 (k->f & f_quiet) ? 0 : pgen_ev, 0))
453 die(EXIT_FAILURE, "RSA key generation failed");
455 /* --- Run a test encryption --- */
458 grand *g = fibrand_create(k->r->ops->word(k->r));
460 mp *m = mprand_range(MP_NEW, rp.n, g, 0);
465 c = rsa_qpubop(&rpp, MP_NEW, m);
466 c = rsa_qprivop(&rp, c, c, g);
469 die(EXIT_FAILURE, "test encryption failed");
475 /* --- Allrighty then --- */
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));
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);
495 static void alg_dsaparam(keyopts *k)
497 static const char *pl[] = { "q", "p", "g", 0 };
498 if (!copyparam(k, pl)) {
507 /* --- Choose appropriate bit lengths if necessary --- */
514 /* --- Allocate a seed block --- */
516 sz = (k->qbits + 7) >> 3;
518 k->r->ops->fill(k->r, p, sz);
520 /* --- Allocate the parameters --- */
522 if (dsa_gen(&dp, k->qbits, k->bits, 0, p, sz, &ds,
523 (k->f & f_quiet) ? 0 : pgen_ev, 0))
524 die(EXIT_FAILURE, "DSA parameter generation failed");
526 /* --- Store the parameters --- */
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));
535 key_setkeydata(k->kf, k->k, kd);
538 /* --- Store the seed for future verification --- */
540 c = base64_class.encoder(0, "", 0);
541 c->ops->code(c, ds.p, ds.sz, &d); c->ops->code(c, 0, 0, &d);
544 key_putattr(k->kf, k->k, "seed", d.buf);
546 dstr_putf(&d, "%u", ds.count);
547 key_putattr(k->kf, k->k, "count", d.buf);
554 static void alg_dsa(keyopts *k)
561 /* --- Get the shared parameters --- */
564 key_split(&k->k->k); kd = k->k->k;
569 /* --- Choose a private key --- */
571 x = mprand_range(MP_NEWSEC, q, k->r, 0);
572 mpmont_create(&mm, p);
573 y = mpmont_exp(&mm, MP_NEW, g, x);
575 /* --- Store everything away --- */
577 key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
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);
584 mp_drop(x); mp_drop(y);
587 static void alg_dhparam(keyopts *k)
589 static const char *pl[] = { "p", "q", "g", 0 };
591 if (!copyparam(k, pl)) {
600 if (STRCMP(k->curve, ==, "list")) {
602 LIST("Built-in prime fields", stdout, ptab[i].name, ptab[i].name);
606 if (dh_parse(&qd, &dp))
607 die(EXIT_FAILURE, "error in field spec: %s", qd.e);
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)
613 moan("WARNING! group check failed: %s", e);
621 /* --- Choose a large safe prime number --- */
623 if (k->f & f_limlee) {
628 rc = dh_limlee(&dp, k->qbits, k->bits,
629 (k->f & f_subgroup) ? DH_SUBGROUP : 0,
630 0, k->r, (k->f & f_quiet) ? 0 : pgen_ev, 0,
631 (k->f & f_quiet) ? 0 : pgen_evspin, 0, &nf, &f);
635 for (i = 0; i < nf; i++) {
638 mp_writedstr(f[i], &d, 10);
641 key_putattr(k->kf, k->k, "factors", d.buf);
644 } else if (k->f & f_kcdsa) {
647 rc = dh_kcdsagen(&dp, k->qbits, k->bits, 0,
648 0, k->r, (k->f & f_quiet) ? 0 : pgen_ev, 0);
653 mp_writedstr(dp.q, &d, 10);
654 mp_div(&v, 0, dp.p, dp.q);
657 mp_writedstr(v, &d, 10);
659 key_putattr(k->kf, k->k, "factors", d.buf);
663 rc = dh_gen(&dp, k->qbits, k->bits, 0, k->r,
664 (k->f & f_quiet) ? 0 : pgen_ev, 0);
667 die(EXIT_FAILURE, "Diffie-Hellman parameter generation failed");
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));
677 key_setkeydata(k->kf, k->k, kd);
682 static void alg_dh(keyopts *k)
689 /* --- Get the shared parameters --- */
692 key_split(&k->k->k); kd = k->k->k;
697 /* --- Choose a suitable private key --- *
699 * Since %$g$% has order %$q$%, choose %$x < q$%.
702 x = mprand_range(MP_NEWSEC, q, k->r, 0);
704 /* --- Compute the public key %$y = g^x \bmod p$% --- */
706 mpmont_create(&mm, p);
707 y = mpmont_exp(&mm, MP_NEW, g, x);
710 /* --- Store everything away --- */
712 key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
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);
719 mp_drop(x); mp_drop(y);
722 static void alg_bbs(keyopts *k)
727 /* --- Sanity checking --- */
733 /* --- Generate the BBS parameters --- */
735 if (bbs_gen(&bp, k->bits, k->r, 0,
736 (k->f & f_quiet) ? 0 : pgen_ev, 0))
737 die(EXIT_FAILURE, "Blum-Blum-Shub key generation failed");
739 /* --- Allrighty then --- */
741 kd = key_newstruct();
742 key_structsteal(kd, "n", key_newmp(KCAT_PUB, bp.n));
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);
755 static void alg_binparam(keyopts *k)
757 static const char *pl[] = { "p", "q", "g", 0 };
758 if (!copyparam(k, pl)) {
765 /* --- Decide on a field --- */
767 if (!k->bits) k->bits = 128;
768 if (k->curve && STRCMP(k->curve, ==, "list")) {
770 LIST("Built-in binary fields", stdout,
771 bintab[i].name, bintab[i].name);
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";
783 "no built-in binary fields provide %u-bit security",
788 /* --- Check it --- */
792 if (dhbin_parse(&qd, &gb))
793 die(EXIT_FAILURE, "error in field spec: %s", qd.e);
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);
802 /* --- Write out the answer --- */
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));
811 key_setkeydata(k->kf, k->k, kd);
816 static void alg_bin(keyopts *k)
823 /* --- Get the shared parameters --- */
826 key_split(&k->k->k); kd = k->k->k;
831 /* --- Choose a suitable private key --- *
833 * Since %$g$% has order %$q$%, choose %$x < q$%.
836 x = mprand_range(MP_NEWSEC, q, k->r, 0);
838 /* --- Compute the public key %$y = g^x \bmod p$% --- */
840 gfreduce_create(&r, p);
841 y = gfreduce_exp(&r, MP_NEW, g, x);
842 gfreduce_destroy(&r);
844 /* --- Store everything away --- */
846 key_structsteal(kd, "y", key_newmp(KCAT_PUB, y));
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);
853 mp_drop(x); mp_drop(y);
856 static void alg_ecparam(keyopts *k)
858 static const char *pl[] = { "curve", 0 };
859 if (!copyparam(k, pl)) {
864 /* --- Decide on a curve --- */
866 if (!k->bits) k->bits = 256;
867 if (k->curve && STRCMP(k->curve, ==, "list")) {
869 LIST("Built-in elliptic curves", stdout,
870 ectab[i].name, ectab[i].name);
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";
883 die(EXIT_FAILURE, "no built-in curves provide %u-bit security",
887 /* --- Check it --- */
889 if ((e = ec_getinfo(&ei, k->curve)) != 0)
890 die(EXIT_FAILURE, "error in curve spec: %s", e);
891 if (!(k->f & f_quiet) && (e = ec_checkinfo(&ei, k->r)) != 0)
892 moan("WARNING! curve check failed: %s", e);
895 /* --- Write out the answer --- */
897 kd = key_newstruct();
898 key_structsteal(kd, "curve", key_newstring(KCAT_SHARE, k->curve));
899 key_setkeydata(k->kf, k->k, kd);
904 static void alg_ec(keyopts *k)
913 /* --- Get the curve --- */
916 key_split(&k->k->k); kd = k->k->k;
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);
924 /* --- Invent a private exponent and compute the public key --- */
926 x = mprand_range(MP_NEWSEC, ei.r, k->r, 0);
927 ec_mul(ei.c, &p, &ei.g, x);
929 /* --- Store everything away --- */
931 key_structsteal(kd, "p", key_newec(KCAT_PUB, &p));
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);
945 _(x25519, X25519, "X25519") \
946 _(x448, X448, "X448")
948 #define XDHALG(xdh, XDH, name) \
950 static void alg_##xdh(keyopts *k) \
952 key_data *kd, *kkd; \
953 octet priv[XDH##_KEYSZ], pub[XDH##_PUBSZ]; \
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))); \
967 key_setkeydata(k->kf, k->k, kd); \
974 _(ed25519, ED25519, "Ed25519") \
975 _(ed448, ED448, "Ed448")
977 #define EDDSAALG(ed, ED, name) \
979 static void alg_##ed(keyopts *k) \
981 key_data *kd, *kkd; \
982 octet priv[ED##_KEYSZ], pub[ED##_PUBSZ]; \
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))); \
996 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 #define XDHTAB(xdh, XDH, name) \
1024 { #xdh, alg_##xdh, "" name " key exchange" },
1027 #define EDDSATAB(ed, ED, name) \
1028 { #ed, alg_##ed, "" name " digital signatures" },
1031 { "empty", alg_empty, "Empty parametrs-only key" },
1035 /* --- @cmd_add@ --- */
1037 static int cmd_add(int argc, char *argv[])
1040 time_t exp = KEXP_EXPIRE;
1041 uint32 kid = rand_global.ops->word(&rand_global);
1042 const char *tag = 0, *ptag = 0;
1044 keyalg *alg = algtab;
1045 const char *rtag = 0;
1046 const struct seedalg *sa = SEEDALG_DEFAULT;
1047 keyopts k = { 0, 0, DSTR_INIT, 0, 0, 0, 0, 0, 0 };
1048 const char *seed = 0;
1051 /* --- Parse options for the subcommand --- */
1054 static struct option opt[] = {
1055 { "algorithm", OPTF_ARGREQ, 0, 'a' },
1056 { "bits", OPTF_ARGREQ, 0, 'b' },
1057 { "qbits", OPTF_ARGREQ, 0, 'B' },
1058 { "parameters", OPTF_ARGREQ, 0, 'p' },
1059 { "expire", OPTF_ARGREQ, 0, 'e' },
1060 { "comment", OPTF_ARGREQ, 0, 'c' },
1061 { "tag", OPTF_ARGREQ, 0, 't' },
1062 { "retag", 0, 0, 'r' },
1063 { "rand-id", OPTF_ARGREQ, 0, 'R' },
1064 { "key-id", OPTF_ARGREQ, 0, 'I' },
1065 { "curve", OPTF_ARGREQ, 0, 'C' },
1066 { "seedalg", OPTF_ARGREQ, 0, 'A' },
1067 { "seed", OPTF_ARGREQ, 0, 's' },
1068 { "newseed", OPTF_ARGREQ, 0, 'n' },
1069 { "public-exponent", OPTF_ARGREQ, 0, 'E' },
1070 { "lock", 0, 0, 'l' },
1071 { "quiet", 0, 0, 'q' },
1072 { "lim-lee", 0, 0, 'L' },
1073 { "subgroup", 0, 0, 'S' },
1074 { "kcdsa", 0, 0, 'K' },
1077 int i = mdwopt(argc, argv, "+a:b:B:p:e:c:t:R:I:C:A:s:n:E:lqrLKS",
1082 /* --- Handle the various options --- */
1086 /* --- Read an algorithm name --- */
1090 size_t sz = strlen(optarg);
1092 if (STRCMP(optarg, ==, "list")) {
1093 for (a = algtab; a->name; a++)
1094 printf("%-10s %s\n", a->name, a->help);
1099 for (a = algtab; a->name; a++) {
1100 if (STRNCMP(optarg, ==, a->name, sz)) {
1101 if (a->name[sz] == 0) {
1105 die(EXIT_FAILURE, "ambiguous algorithm name `%s'", optarg);
1111 die(EXIT_FAILURE, "unknown algorithm name `%s'", optarg);
1114 /* --- Bits must be nonzero and a multiple of 8 --- */
1118 k.bits = strtoul(optarg, &p, 0);
1119 if (k.bits == 0 || *p != 0)
1120 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1125 k.qbits = strtoul(optarg, &p, 0);
1126 if (k.qbits == 0 || *p != 0)
1127 die(EXIT_FAILURE, "bad bitlength `%s'", optarg);
1130 /* --- Parameter selection --- */
1136 /* --- Expiry dates get passed to @get_date@ for parsing --- */
1139 if (STRCMP(optarg, ==, "forever"))
1142 exp = get_date(optarg, 0);
1144 die(EXIT_FAILURE, "bad expiry date `%s'", optarg);
1148 /* --- Store comments without interpretation --- */
1151 if (key_chkcomment(optarg))
1152 die(EXIT_FAILURE, "bad comment string `%s'", optarg);
1156 /* --- Elliptic curve parameters --- */
1162 /* --- Store tags --- */
1165 if (key_chkident(optarg))
1166 die(EXIT_FAILURE, "bad tag string `%s'", optarg);
1173 /* --- Seeding --- */
1176 const struct seedalg *ss;
1177 if (STRCMP(optarg, ==, "list")) {
1178 printf("Seed algorithms:\n");
1179 for (ss = seedtab; ss->p; ss++)
1180 printf(" %s\n", ss->p);
1183 if (seed) die(EXIT_FAILURE, "seed already set -- put -A first");
1185 for (ss = seedtab; ss->p; ss++) {
1186 if (STRCMP(optarg, ==, ss->p))
1190 die(EXIT_FAILURE, "seed algorithm `%s' not known", optarg);
1197 if (seed) die(EXIT_FAILURE, "seed already set");
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));
1203 k.r = sa->gen(d.buf, d.len);
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);
1215 if (seed) die(EXIT_FAILURE, "seed already set");
1218 rand_get(RAND_GLOBAL, p, n);
1219 c = base64_class.encoder(0, "", 0);
1220 c->ops->code(c, p, n, &d); c->ops->code(c, 0, 0, &d);
1223 k.r = sa->gen(p, n);
1226 /* --- Key id --- */
1233 id = strtoul(optarg, &p, 16);
1234 if (errno || *p || id > MASK32)
1235 die(EXIT_FAILURE, "bad key-id `%s'", optarg);
1239 /* --- Public exponent --- */
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);
1248 /* --- Other flags --- */
1269 /* --- Other things are bogus --- */
1277 /* --- Various sorts of bogosity --- */
1279 if ((k.f & f_bogus) || optind + 1 > argc) {
1281 "Usage: add [OPTIONS] TYPE [ATTR...]");
1283 if (key_chkident(argv[optind]))
1284 die(EXIT_FAILURE, "bad key type `%s'", argv[optind]);
1286 /* --- Set up various bits of the state --- */
1288 if (exp == KEXP_EXPIRE)
1289 exp = time(0) + 14 * 24 * 60 * 60;
1291 /* --- Open the file and create the basic key block --- *
1293 * Keep on generating keyids until one of them doesn't collide.
1296 doopen(&f, KOPEN_WRITE);
1299 /* --- Key the generator --- */
1305 if ((err = key_new(&f, kid, argv[optind], exp, &k.k)) == 0)
1307 else if (err != KERR_DUPID)
1308 die(EXIT_FAILURE, "error adding new key: %s", key_strerror(err));
1311 /* --- Set various simple attributes --- */
1316 if (k.f & f_retag) {
1317 if ((kk = key_bytag(&f, tag)) != 0 &&
1319 STRCMP(kk->tag, ==, tag))
1320 key_settag(&f, kk, 0);
1322 if ((err = key_settag(&f, k.k, tag)) != 0)
1323 die(EXIT_FAILURE, "error setting key tag: %s", key_strerror(err));
1327 int err = key_setcomment(&f, k.k, c);
1329 die(EXIT_FAILURE, "error setting key comment: %s", key_strerror(err));
1332 setattr(&f, k.k, argv + optind + 1);
1334 key_putattr(&f, k.k, "genseed", seed);
1335 key_putattr(&f, k.k, "seedalg", sa->p);
1338 key_fulltag(k.k, &k.tag);
1340 /* --- Find the parameter key --- */
1342 if (ptag && (k.p = key_bytag(&f, ptag)) == 0)
1343 die(EXIT_FAILURE, "parameter key `%s' not found", ptag);
1345 /* --- Now generate the actual key data --- */
1351 dstr_destroy(&k.tag);
1356 /*----- Key listing -------------------------------------------------------*/
1358 /* --- Listing options --- */
1360 typedef 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 */
1368 /* --- Listing flags --- */
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 */
1374 /* --- @showkeydata@ --- *
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
1383 * Use: Emits a piece of key data in a human-readable format.
1386 static void showkeydata(key_data *k, int ind, listopts *o, dstr *d)
1388 #define INDENT(i) do { \
1390 for (_i = 0; _i < (i); _i++) { \
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; }
1400 switch (k->e & KF_ENCMASK) {
1402 /* --- Binary key data --- *
1404 * Emit as a simple hex dump.
1408 const octet *p = k->u.k.k;
1409 const octet *l = p + k->u.k.sz;
1412 fputs(" {", stdout);
1417 } else if (sz % 8 == 0)
1421 printf("%02x", *p++);
1426 fputs("}\n", stdout);
1429 /* --- Encrypted data --- *
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.
1435 case KENC_ENCRYPT: {
1437 if (key_punlock(&kd, k, d->buf))
1438 printf(" <failed to unlock %s>\n", d->buf);
1440 fputs(" encrypted", stdout);
1441 showkeydata(kd, ind, o, d);
1446 /* --- Integer keys --- *
1448 * Emit as a large integer in decimal. This makes using the key in
1449 * `calc' or whatever easier.
1454 mp_writefile(k->u.m, stdout, 10);
1458 /* --- Strings --- */
1461 printf(" `%s'\n", k->u.p);
1464 /* --- Elliptic curve points --- */
1467 if (EC_ATINF(&k->u.e))
1468 fputs(" inf\n", stdout);
1470 fputs(" 0x", stdout); mp_writefile(k->u.e.x, stdout, 16);
1471 fputs(", 0x", stdout); mp_writefile(k->u.e.y, stdout, 16);
1476 /* --- Structured keys --- *
1478 * Just iterate over the subkeys.
1486 fputs(" {\n", stdout);
1487 for (key_mksubkeyiter(&i, k); key_nextsubkey(&i, &tag, &k); ) {
1488 if (!key_match(k, &o->kf))
1491 printf("%s =", tag);
1493 dstr_putf(d, ".%s", tag);
1494 showkeydata(k, ind + 2, o, d);
1497 fputs("}\n", stdout);
1504 /* --- @showkey@ --- *
1506 * Arguments: @key *k@ = pointer to key to show
1507 * @listopts *o@ = pointer to listing options
1511 * Use: Emits a listing of a particular key.
1514 static void showkey(key *k, listopts *o)
1516 char ebuf[24], dbuf[24];
1519 /* --- Skip the key if the filter doesn't match --- */
1521 if (!key_match(k->k, &o->kf))
1524 /* --- Sort out the expiry and deletion times --- */
1526 if (KEY_EXPIRED(o->t, k->exp))
1527 strcpy(ebuf, "expired");
1528 else if (k->exp == KEXP_FOREVER)
1529 strcpy(ebuf, "forever");
1531 tm = (o->f & f_utc) ? gmtime(&k->exp) : localtime(&k->exp);
1532 strftime(ebuf, sizeof(ebuf), o->tfmt, tm);
1535 if (KEY_EXPIRED(o->t, k->del))
1536 strcpy(dbuf, "deleted");
1537 else if (k->del == KEXP_FOREVER)
1538 strcpy(dbuf, "forever");
1540 tm = (o->f & f_utc) ? gmtime(&k->del) : localtime(&k->del);
1541 strftime(dbuf, sizeof(dbuf), o->tfmt, tm);
1544 /* --- If in compact format, just display and quit --- */
1547 if (!(o->f & f_newline)) {
1548 printf("%8s %-20s %-20s %-10s %s\n",
1549 "Id", "Tag", "Type", "Expire", "Delete");
1551 printf("%08lx %-20s %-20s %-10s %s\n",
1552 (unsigned long)k->id, k->tag ? k->tag : "<none>",
1553 k->type, ebuf, dbuf);
1558 /* --- Display the standard header --- */
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>");
1569 /* --- Display the attributes --- */
1573 const char *av, *an;
1576 printf("attributes:");
1577 for (key_mkattriter(&i, k); key_nextattr(&i, &an, &av); ) {
1578 printf("\n %s = %s", an, av);
1582 fputc('\n', stdout);
1587 /* --- If dumping requested, dump the raw key data --- */
1591 fputs("key:", stdout);
1593 showkeydata(k->k, 0, o, &d);
1600 /* --- @cmd_list@ --- */
1602 static int cmd_list(int argc, char *argv[])
1606 listopts o = { 0, 0, 0, 0, { 0, 0 } };
1608 /* --- Parse subcommand options --- */
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' },
1618 int i = mdwopt(argc, argv, "+uqvf:", opt, 0, 0, 0);
1635 int e = key_readflags(optarg, &p, &o.kf.f, &o.kf.m);
1637 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1646 die(EXIT_FAILURE, "Usage: list [-uqv] [-f FILTER] [TAG...]");
1648 /* --- Open the key file --- */
1650 doopen(&f, KOPEN_READ);
1653 /* --- Set up the time format --- */
1656 o.tfmt = "%Y-%m-%d";
1657 else if (o.f & f_utc)
1658 o.tfmt = "%Y-%m-%d %H:%M:%S UTC";
1660 o.tfmt = "%Y-%m-%d %H:%M:%S %Z";
1662 /* --- If specific keys were requested use them, otherwise do all --- *
1664 * Some day, this might turn into a wildcard match.
1667 if (optind < argc) {
1669 if ((k = key_bytag(&f, argv[optind])) != 0)
1672 moan("key `%s' not found", argv[optind]);
1676 } while (optind < argc);
1679 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1687 return (EXIT_FAILURE);
1692 /*----- Command implementation --------------------------------------------*/
1694 /* --- @cmd_expire@ --- */
1696 static int cmd_expire(int argc, char *argv[])
1704 die(EXIT_FAILURE, "Usage: expire TAG...");
1705 doopen(&f, KOPEN_WRITE);
1706 for (i = 1; i < argc; i++) {
1707 if ((k = key_bytag(&f, argv[i])) != 0)
1710 moan("key `%s' not found", argv[i]);
1718 /* --- @cmd_delete@ --- */
1720 static int cmd_delete(int argc, char *argv[])
1728 die(EXIT_FAILURE, "Usage: delete TAG...");
1729 doopen(&f, KOPEN_WRITE);
1730 for (i = 1; i < argc; i++) {
1731 if ((k = key_bytag(&f, argv[i])) != 0)
1734 moan("key `%s' not found", argv[i]);
1742 /* --- @cmd_setattr@ --- */
1744 static int cmd_setattr(int argc, char *argv[])
1750 die(EXIT_FAILURE, "Usage: setattr TAG ATTR...");
1751 doopen(&f, KOPEN_WRITE);
1752 if ((k = key_bytag(&f, argv[1])) == 0)
1753 die(EXIT_FAILURE, "key `%s' not found", argv[1]);
1754 setattr(&f, k, argv + 2);
1759 /* --- @cmd_getattr@ --- */
1761 static int cmd_getattr(int argc, char *argv[])
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]);
1774 if ((p = key_getattr(&f, k, argv[2])) == 0)
1775 die(EXIT_FAILURE, "no attribute `%s' for key `%s'", argv[2], d.buf);
1782 /* --- @cmd_finger@ --- */
1784 static const struct fpres {
1786 const codec_class *cdc;
1787 unsigned short ival;
1790 { "hex", &hex_class, 8, "-:" },
1791 { "base32", &base32_class, 6, ":" },
1795 static void fingerprint(key *k, const struct fpres *fpres,
1796 const gchash *ch, const key_filter *kf)
1799 dstr d = DSTR_INIT, dd = DSTR_INIT;
1805 if (key_fingerprint(k, h, kf)) {
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);
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]);
1814 dstr_putc(&d, ' '); key_fulltag(k, &d); dstr_putc(&d, '\n');
1815 dstr_write(&d, stdout);
1817 dstr_destroy(&d); dstr_destroy(&dd);
1821 static const struct fpres *lookup_fpres(const char *name)
1823 const struct fpres *fpres;
1824 for (fpres = fprestab; fpres->name; fpres++)
1825 if (STRCMP(fpres->name, ==, name)) return (fpres);
1826 die(EXIT_FAILURE, "unknown presentation syle `%s'", name);
1829 static int cmd_finger(int argc, char *argv[])
1833 const struct fpres *fpres = fprestab;
1834 const gchash *ch = &rmd160;
1835 key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1838 static struct option opt[] = {
1839 { "filter", OPTF_ARGREQ, 0, 'f' },
1840 { "presentation", OPTF_ARGREQ, 0, 'p' },
1841 { "algorithm", OPTF_ARGREQ, 0, 'a' },
1844 int i = mdwopt(argc, argv, "+f:a:p:", opt, 0, 0, 0);
1850 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1852 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1855 fpres = lookup_fpres(optarg);
1858 if ((ch = ghash_byname(optarg)) == 0)
1859 die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1867 argv += optind; argc -= optind;
1870 "Usage: fingerprint [-a HASH] [-p STYLE] [-f FILTER] [TAG...]");
1873 doopen(&f, KOPEN_READ);
1877 for (i = 0; i < argc; i++) {
1878 key *k = key_bytag(&f, argv[i]);
1880 fingerprint(k, fpres, ch, &kf);
1883 moan("key `%s' not found", argv[i]);
1889 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
1890 fingerprint(k, fpres, ch, &kf);
1895 /* --- @cmd_verify@ --- */
1897 static int cmd_verify(int argc, char *argv[])
1901 const gchash *ch = &rmd160;
1905 dstr d = DSTR_INIT, dd = DSTR_INIT;
1908 const struct fpres *fpres = fprestab;
1909 key_filter kf = { KF_NONSECRET, KF_NONSECRET };
1912 static struct option opt[] = {
1913 { "filter", OPTF_ARGREQ, 0, 'f' },
1914 { "presentation", OPTF_ARGREQ, 0, 'p' },
1915 { "algorithm", OPTF_ARGREQ, 0, 'a' },
1918 int i = mdwopt(argc, argv, "+f:a:p:", opt, 0, 0, 0);
1924 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
1926 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
1929 fpres = lookup_fpres(optarg);
1932 if ((ch = ghash_byname(optarg)) == 0)
1933 die(EXIT_FAILURE, "unknown hash algorithm `%s'", optarg);
1941 argv += optind; argc -= optind;
1942 if (rc || argc != 2) {
1944 "Usage: verify [-a HASH] [-p STYLE] [-f FILTER] TAG FINGERPRINT");
1947 doopen(&f, KOPEN_READ);
1949 if ((k = key_bytag(&f, argv[0])) == 0)
1950 die(EXIT_FAILURE, "key `%s' not found", argv[0]);
1951 for (p = argv[1]; *p; p++) {
1952 if (strchr(fpres->sep, *p)) continue;
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));
1961 if (d.len != ch->hashsz) {
1962 die(EXIT_FAILURE, "incorrect fingerprint length (%lu != %lu)",
1963 (unsigned long)d.len, (unsigned long)ch->hashsz);
1966 if (!key_fingerprint(k, h, &kf))
1967 die(EXIT_FAILURE, "key has no fingerprintable components (as filtered)");
1968 fpr = GH_DONE(h, 0);
1969 if (MEMCMP(fpr, !=, d.buf, ch->hashsz))
1970 die(EXIT_FAILURE, "key fingerprint mismatch");
1971 dstr_destroy(&d); dstr_destroy(&dd);
1976 /* --- @cmd_comment@ --- */
1978 static int cmd_comment(int argc, char *argv[])
1984 if (argc < 2 || argc > 3)
1985 die(EXIT_FAILURE, "Usage: comment TAG [COMMENT]");
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));
1995 /* --- @cmd_tag@ --- */
1997 static int cmd_tag(int argc, char *argv[])
2006 static struct option opt[] = {
2007 { "retag", 0, 0, 'r' },
2010 int i = mdwopt(argc, argv, "+r", opt, 0, 0, 0);
2023 argv += optind; argc -= optind;
2024 if (argc < 1 || argc > 2 || rc)
2025 die(EXIT_FAILURE, "Usage: tag [-r] TAG [NEW-TAG]");
2026 doopen(&f, KOPEN_WRITE);
2027 if (flags & f_retag) {
2028 if ((k = key_bytag(&f, argv[1])) != 0 && STRCMP(k->tag, ==, argv[1]))
2029 key_settag(&f, k, 0);
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));
2039 /* --- @cmd_lock@ --- */
2041 static int cmd_lock(int argc, char *argv[])
2049 die(EXIT_FAILURE, "Usage: lock QTAG");
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]);
2053 if ((*kd)->e == KENC_ENCRYPT && key_punlock(kd, 0, d.buf))
2054 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
2055 if (key_plock(kd, 0, d.buf))
2056 die(EXIT_FAILURE, "failed to lock key `%s'", d.buf);
2062 /* --- @cmd_unlock@ --- */
2064 static int cmd_unlock(int argc, char *argv[])
2072 die(EXIT_FAILURE, "Usage: unlock QTAG");
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]);
2076 if ((*kd)->e != KENC_ENCRYPT)
2077 die(EXIT_FAILURE, "key `%s' is not encrypted", d.buf);
2078 if (key_punlock(kd, 0, d.buf))
2079 die(EXIT_FAILURE, "couldn't unlock key `%s'", d.buf);
2085 /* --- @cmd_extract@ --- */
2087 static int cmd_extract(int argc, char *argv[])
2093 key_filter kf = { 0, 0 };
2095 const char *outfile = 0;
2099 static struct option opt[] = {
2100 { "filter", OPTF_ARGREQ, 0, 'f' },
2103 int i = mdwopt(argc, argv, "f:", opt, 0, 0, 0);
2109 int err = key_readflags(optarg, &p, &kf.f, &kf.m);
2111 die(EXIT_FAILURE, "bad filter string `%s'", optarg);
2119 argv += optind; argc -= optind;
2121 die(EXIT_FAILURE, "Usage: extract [-f FILTER] FILE [TAG...]");
2122 if (STRCMP(*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));
2133 doopen(&f, KOPEN_READ);
2137 for (key_mkiter(&i, &f); (k = key_next(&i)) != 0; )
2138 key_extract(&f, k, fp, &kf);
2140 for (i = 1; i < argc; i++) {
2141 if ((k = key_bytag(&f, argv[i])) != 0)
2142 key_extract(&f, k, fp, &kf);
2144 moan("key `%s' not found", argv[i]);
2149 if (fclose(fp) || (outfile && rename(d.buf, outfile)))
2150 die(EXIT_FAILURE, "error writing file: %s", strerror(errno));
2156 /* --- @cmd_tidy@ --- */
2158 static int cmd_tidy(int argc, char *argv[])
2162 die(EXIT_FAILURE, "Usage: tidy");
2163 doopen(&f, KOPEN_WRITE);
2164 f.f |= KF_MODIFIED; /* Nasty hack */
2169 /* --- @cmd_merge@ --- */
2171 static int cmd_merge(int argc, char *argv[])
2177 die(EXIT_FAILURE, "Usage: merge FILE");
2178 if (STRCMP(argv[1], ==, "-"))
2180 else if (!(fp = fopen(argv[1], "r"))) {
2181 die(EXIT_FAILURE, "couldn't open `%s' for reading: %s",
2182 argv[1], strerror(errno));
2185 doopen(&f, KOPEN_WRITE);
2186 key_merge(&f, argv[1], fp, key_moan, 0);
2191 /* --- @cmd_show@ --- */
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) \
2200 LI("Prime Diffie-Hellman groups", dh, \
2201 ptab[i].name, ptab[i].name) \
2202 LI("Binary Diffie-Hellman groups", bindh, \
2203 bintab[i].name, bintab[i].name) \
2204 LI("Key-generation algorithms", keygen, \
2205 algtab[i].name, algtab[i].name) \
2206 LI("Random seeding algorithms", seed, \
2207 seedtab[i].p, seedtab[i].p) \
2208 LI("Fingerprint presentation styles", fpres, \
2209 fprestab[i].name, fprestab[i].name)
2211 MAKELISTTAB(listtab, LISTS)
2213 static int cmd_show(int argc, char *argv[])
2215 return (displaylists(listtab, argv + 1));
2218 /*----- Main command table ------------------------------------------------*/
2220 static int cmd_help(int argc, char *argv[]);
2222 static cmd cmds[] = {
2223 { "help", cmd_help, "help [COMMAND...]" },
2224 { "show", cmd_show, "show [ITEM...]" },
2225 { "list", cmd_list, "list [-uqv] [-f FILTER] [TAG...]", "\
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\
2232 { "fingerprint", cmd_finger,
2233 "fingerprint [-a HASH] [-p STYLE] [-f FILTER] [TAG...]", "\
2236 -f, --filter=FILT Only hash key components matching FILT.\n\
2237 -p, --presentation=STYLE Use STYLE for presenting fingerprints.\n\
2238 -a, --algorithm=HASH Use the named HASH algorithm.\n\
2239 ($ show hash for list.)\n\
2241 { "verify", cmd_verify,
2242 "verify [-a HASH] [-p STYLE] [-f FILTER] TAG FINGERPRINT", "\
2245 -f, --filter=FILT Only hash key components matching FILT.\n\
2246 -p, --presentation=STYLE Expect FINGERPRINT in the given STYLE.\n\
2247 -a, --algorithm=HASH Use the named HASH algorithm.\n\
2248 ($ show hash for list.)\n\
2250 { "extract", cmd_extract, "extract [-f FILTER] FILE [TAG...]", "\
2253 -f, --filter=FILT Only extract key components matching FILT.\n\
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..." },
2259 { "getattr", cmd_getattr, "getattr TAG ATTR" },
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]", "\
2266 -r, --retag Untag any key currently called new-tag.\n\
2268 { "tidy", cmd_tidy, "tidy" },
2270 "add [-OPTIONS] TYPE [ATTR...]\n\
2271 Options: [-lqrLKS] [-a ALG] [-bB BITS] [-E PUBEXP] [-p PARAM] [-R TAG]\n\
2272 [-A SEEDALG] [-s SEED] [-n BITS] [-I KEYID]\n\
2273 [-e EXPIRE] [-t TAG] [-c COMMENT]", "\
2276 -a, --algorithm=ALG Generate keys suitable for ALG.\n\
2277 ($ show keygen for list.)\n\
2278 -b, --bits=N Generate an N-bit key.\n\
2279 -B, --qbits=N Use an N-bit subgroup or factors.\n\
2280 -E, --public-exponent=E Use E as RSA public exponent (default 65537)\n\
2281 -p, --parameters=TAG Get group parameters from TAG.\n\
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\
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\
2293 -I, --key-id=ID Force the key-id for the new key.\n\
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\
2297 -K, --kcdsa Generate KCDSA-style Lim-Lee primes for DH groups.\n\
2298 -S, --subgroup Use a prime-order subgroup for Diffie-Hellman.\n\
2303 static int cmd_help(int argc, char *argv[])
2305 sc_help(cmds, stdout, argv + 1);
2309 /*----- Main code ---------------------------------------------------------*/
2311 /* --- Helpful GNUy functions --- */
2313 static void usage(FILE *fp)
2315 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
2318 void version(FILE *fp)
2320 pquis(fp, "$, Catacomb version " VERSION "\n");
2323 void help_global(FILE *fp)
2327 Performs various simple key management operations.\n\
2329 Global command line options:\n\
2331 -h, --help [COMMAND...] Display this help text (or help for COMMANDs).\n\
2332 -v, --version Display version number.\n\
2333 -u, --usage Display short usage summary.\n\
2335 -k, --keyring=FILE Read and write keys in FILE.\n",
2341 * Arguments: @int argc@ = number of command line arguments
2342 * @char *argv[]@ = array of command line arguments
2344 * Returns: Nonzero on failure.
2346 * Use: Main program. Performs simple key management functions.
2349 int main(int argc, char *argv[])
2355 /* --- Initialization --- */
2360 /* --- Parse command line options --- */
2363 static struct option opt[] = {
2365 /* --- Standard GNUy help options --- */
2367 { "help", 0, 0, 'h' },
2368 { "version", 0, 0, 'v' },
2369 { "usage", 0, 0, 'u' },
2371 /* --- Real live useful options --- */
2373 { "keyring", OPTF_ARGREQ, 0, 'k' },
2375 /* --- Magic terminator --- */
2379 int i = mdwopt(argc, argv, "+hvu k:", opt, 0, 0, 0);
2385 /* --- GNU help options --- */
2388 sc_help(cmds, stdout, argv + optind);
2397 /* --- Real useful options --- */
2403 /* --- Bogosity --- */
2411 /* --- Complain about excessive bogons --- */
2413 if (f & f_bogus || optind == argc) {
2418 /* --- Initialize the Catacomb random number generator --- */
2420 rand_noisesrc(RAND_GLOBAL, &noise_source);
2421 rand_seed(RAND_GLOBAL, 160);
2423 /* --- Dispatch to appropriate command handler --- */
2428 return (findcmd(cmds, argv[0])->cmd(argc, argv));
2431 /*----- That's all, folks -------------------------------------------------*/