3 * $Id: keyutil.c,v 1.17 2004/03/28 01:58:47 mdw Exp $
5 * Simple key manager program
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of Catacomb.
14 * Catacomb is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
19 * Catacomb is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
24 * You should have received a copy of the GNU Library General Public
25 * License along with Catacomb; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
30 /*----- Revision history --------------------------------------------------*
33 * Revision 1.17 2004/03/28 01:58:47 mdw
34 * Generate, store and retreive elliptic curve keys.
36 * Revision 1.16 2003/10/15 09:31:45 mdw
39 * Revision 1.15 2003/05/15 23:23:24 mdw
40 * Fix behaviour with bogus trailing attributes.
42 * Revision 1.14 2001/02/23 09:03:27 mdw
43 * Simplify usage message by removing nonexistant options.
45 * Revision 1.13 2001/02/21 20:04:27 mdw
46 * Provide help on individual commands (some need it desparately). Allow
47 * atomic retagging of keys.
49 * Revision 1.12 2001/02/03 11:58:22 mdw
50 * Store the correct seed information and count for DSA keys now that it's
53 * Revision 1.11 2000/12/06 20:33:27 mdw
54 * Make flags be macros rather than enumerations, to ensure that they're
57 * Revision 1.10 2000/10/08 12:02:21 mdw
58 * Use @MP_EQ@ instead of @MP_CMP@.
60 * Revision 1.9 2000/08/15 21:40:49 mdw
61 * Minor formatting change in listing attributes.
63 * Revision 1.8 2000/07/29 09:59:13 mdw
64 * Support Lim-Lee primes in Diffie-Hellman parameter generation.
66 * Revision 1.7 2000/07/01 11:18:51 mdw
67 * Use new interfaces for key manipulation.
69 * Revision 1.6 2000/06/17 11:28:22 mdw
70 * Use secure memory interface from MP library. `rand_getgood' is
73 * Revision 1.5 2000/02/12 18:21:03 mdw
74 * Overhaul of key management (again).
76 * Revision 1.4 1999/12/22 15:48:10 mdw
77 * Track new key-management changes. Support new key generation
80 * Revision 1.3 1999/11/02 15:23:24 mdw
81 * Fix newlines in keyring list.
83 * Revision 1.2 1999/10/15 21:05:28 mdw
84 * In `key list', show timezone for local times, and support `-u' option
87 * Revision 1.1 1999/09/03 08:41:12 mdw
92 /*----- Header files ------------------------------------------------------*/
102 #include <mLib/base64.h>
103 #include <mLib/mdwopt.h>
104 #include <mLib/quis.h>
105 #include <mLib/report.h>
106 #include <mLib/sub.h>
127 /*----- Handy global state ------------------------------------------------*/
129 static const char *keyfile
= "keyring";
131 /*----- Useful shared functions -------------------------------------------*/
133 /* --- @doopen@ --- *
135 * Arguments: @key_file *f@ = pointer to key file block
136 * @unsigned how@ = method to open file with
140 * Use: Opens a key file and handles errors by panicking
144 static void doopen(key_file
*f
, unsigned how
)
146 if (key_open(f
, keyfile
, how
, key_moan
, 0))
147 die(1, "couldn't open keyring `%s': %s", keyfile
, strerror(errno
));
150 /* --- @doclose@ --- *
152 * Arguments: @key_file *f@ = pointer to key file block
156 * Use: Closes a key file and handles errors by panicking
160 static void doclose(key_file
*f
)
162 switch (key_close(f
)) {
164 die(EXIT_FAILURE
, "couldn't write file `%s': %s",
165 keyfile
, strerror(errno
));
167 die(EXIT_FAILURE
, "keyring file `%s' broken: %s (repair manually)",
168 keyfile
, strerror(errno
));
172 /* --- @setattr@ --- *
174 * Arguments: @key_file *f@ = pointer to key file block
175 * @key *k@ = pointer to key block
176 * @char *v[]@ = array of assignments (overwritten!)
180 * Use: Applies the attribute assignments to the key.
183 static void setattr(key_file
*f
, key
*k
, char *v
[])
188 size_t eq
= strcspn(p
, "=");
190 moan("invalid assignment: `%s' (ignored)", p
);
196 if ((err
= key_putattr(f
, k
, *v
, *p ? p
: 0)) != 0)
197 die(EXIT_FAILURE
, "couldn't set attributes: %s", key_strerror(err
));
202 /*----- Key generation ----------------------------------------------------*/
204 /* --- Key generation parameters --- */
206 typedef struct keyopts
{
207 key_file
*kf
; /* Pointer to key file */
208 key
*k
; /* Pointer to the actual key */
209 dstr tag
; /* Full tag name for the key */
210 unsigned f
; /* Flags for the new key */
211 unsigned bits
, qbits
; /* Bit length for the new key */
212 const char *curve
; /* Elliptic curve name/info */
213 key
*p
; /* Parameters key-data */
216 #define f_bogus 1u /* Error in parsing */
217 #define f_lock 2u /* Passphrase-lock private key */
218 #define f_quiet 4u /* Don't show a progress indicator */
219 #define f_limlee 8u /* Generate Lim-Lee primes */
220 #define f_subgroup 16u /* Generate a subgroup */
221 #define f_retag 32u /* Remove any existing tag */
223 /* --- @dolock@ --- *
225 * Arguments: @keyopts *k@ = key generation options
226 * @key_data *kd@ = pointer to key data to lock
227 * @const char *t@ = tag suffix or null
231 * Use: Does passphrase locking on new keys.
234 static void dolock(keyopts
*k
, key_data
*kd
, const char *t
)
236 if (!(k
->f
& f_lock
))
239 dstr_putf(&k
->tag
, ".%s", t
);
240 if (key_plock(k
->tag
.buf
, kd
, kd
))
241 die(EXIT_FAILURE
, "couldn't lock key");
246 * Arguments: @key_data *kd@ = pointer to parent key block
247 * @const char *tag@ = pointer to tag string
248 * @mp *m@ = integer to store
249 * @unsigned f@ = flags to set
253 * Use: Sets a multiprecision integer subkey.
256 static void mpkey(key_data
*kd
, const char *tag
, mp
*m
, unsigned f
)
258 key_data
*kkd
= key_structcreate(kd
, tag
);
263 /* --- @copyparam@ --- *
265 * Arguments: @keyopts *k@ = pointer to key options
266 * @const char **pp@ = checklist of parameters
268 * Returns: Nonzero if parameters copied; zero if you have to generate
271 * Use: Copies parameters from a source key to the current one.
274 static int copyparam(keyopts
*k
, const char **pp
)
278 /* --- Quick check if no parameters supplied --- */
283 /* --- Run through the checklist --- */
286 key_data
*kd
= key_structfind(&k
->p
->k
, *pp
);
288 die(EXIT_FAILURE
, "bad parameter key: parameter `%s' not found", *pp
);
289 if ((kd
->e
& KF_CATMASK
) != KCAT_SHARE
)
290 die(EXIT_FAILURE
, "bad parameter key: subkey `%s' is not shared", *pp
);
294 /* --- Copy over the parameters --- */
298 if (!key_copy(&k
->k
->k
, &k
->p
->k
, &kf
))
299 die(EXIT_FAILURE
, "unexpected failure while copying parameters");
305 * Arguments: @key_data *k@ = pointer to key data block
306 * @const char *tag@ = tag string to use
308 * Returns: Pointer to multiprecision integer key item.
310 * Use: Fetches an MP key component.
313 static mp
*getmp(key_data
*k
, const char *tag
)
315 k
= key_structfind(k
, tag
);
317 die(EXIT_FAILURE
, "unexpected failure looking up subkey `%s'", tag
);
318 if ((k
->e
& KF_ENCMASK
) != KENC_MP
)
319 die(EXIT_FAILURE
, "subkey `%s' has an incompatible type");
323 /* --- @keyrand@ --- *
325 * Arguments: @key_file *kf@ = pointer to key file
326 * @const char *id@ = pointer to key id (or null)
330 * Use: Keys the random number generator.
333 static void keyrand(key_file
*kf
, const char *id
)
337 /* --- Find the key --- */
340 if ((k
= key_bytag(kf
, id
)) == 0)
341 die(EXIT_FAILURE
, "key `%s' not found", id
);
343 k
= key_bytype(kf
, "catacomb-rand");
346 key_data
*kd
= &k
->k
, kkd
;
349 switch (kd
->e
& KF_ENCMASK
) {
355 if (key_punlock(d
.buf
, kd
, &kkd
))
356 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
);
375 /* --- Key generation algorithms --- */
377 static void alg_binary(keyopts
*k
)
386 die(EXIT_FAILURE
, "no shared parameters for binary keys");
388 sz
= (k
->bits
+ 7) >> 3;
390 m
= (1 << (((k
->bits
- 1) & 7) + 1)) - 1;
391 rand_get(RAND_GLOBAL
, p
, sz
);
393 key_binary(&k
->k
->k
, p
, sz
);
394 k
->k
->k
.e
|= KCAT_SYMM
| KF_BURN
;
397 dolock(k
, &k
->k
->k
, 0);
400 static void alg_des(keyopts
*k
)
409 die(EXIT_FAILURE
, "no shared parameters for DES keys");
410 if (k
->bits
% 56 || k
->bits
> 168)
411 die(EXIT_FAILURE
, "DES keys must be 56, 112 or 168 bits long");
415 rand_get(RAND_GLOBAL
, p
, sz
); /* Too much work done here! */
416 for (i
= 0; i
< sz
; i
++) {
417 octet x
= p
[i
] | 0x01;
421 p
[i
] = (p
[i
] & 0xfe) | (x
& 0x01);
423 key_binary(&k
->k
->k
, p
, sz
);
424 k
->k
->k
.e
|= KCAT_SYMM
| KF_BURN
;
427 dolock(k
, &k
->k
->k
, 0);
430 static void alg_rsa(keyopts
*k
)
435 /* --- Sanity checking --- */
438 die(EXIT_FAILURE
, "no shared parameters for RSA keys");
442 /* --- Generate the RSA parameters --- */
444 if (rsa_gen(&rp
, k
->bits
, &rand_global
, 0,
445 (k
->f
& f_quiet
) ?
0 : pgen_ev
, 0))
446 die(EXIT_FAILURE
, "RSA key generation failed");
448 /* --- Run a test encryption --- */
451 grand
*g
= fibrand_create(rand_global
.ops
->word(&rand_global
));
453 mp
*m
= mprand_range(MP_NEW
, rp
.n
, g
, 0);
458 c
= rsa_qpubop(&rpp
, MP_NEW
, m
);
459 c
= rsa_qprivop(&rp
, c
, c
, g
);
462 die(EXIT_FAILURE
, "test encryption failed");
468 /* --- Allrighty then --- */
472 mpkey(kd
, "n", rp
.n
, KCAT_PUB
);
473 mpkey(kd
, "e", rp
.e
, KCAT_PUB
);
475 kd
= key_structcreate(kd
, "private");
477 mpkey(kd
, "d", rp
.d
, KCAT_PRIV
| KF_BURN
);
478 mpkey(kd
, "p", rp
.p
, KCAT_PRIV
| KF_BURN
);
479 mpkey(kd
, "q", rp
.q
, KCAT_PRIV
| KF_BURN
);
480 mpkey(kd
, "q-inv", rp
.q_inv
, KCAT_PRIV
| KF_BURN
);
481 mpkey(kd
, "d-mod-p", rp
.dp
, KCAT_PRIV
| KF_BURN
);
482 mpkey(kd
, "d-mod-q", rp
.dq
, KCAT_PRIV
| KF_BURN
);
483 dolock(k
, kd
, "private");
488 static void alg_dsaparam(keyopts
*k
)
490 static const char *pl
[] = { "q", "p", "g", 0 };
491 if (!copyparam(k
, pl
)) {
497 key_data
*kd
= &k
->k
->k
;
500 /* --- Choose appropriate bit lengths if necessary --- */
507 /* --- Allocate a seed block --- */
509 sz
= (k
->qbits
+ 7) >> 3;
511 rand_get(RAND_GLOBAL
, p
, sz
);
513 /* --- Allocate the parameters --- */
515 if (dsa_gen(&dp
, k
->qbits
, k
->bits
, 0, p
, sz
, &ds
,
516 (k
->f
& f_quiet
) ?
0 : pgen_ev
, 0))
517 die(EXIT_FAILURE
, "DSA parameter generation failed");
519 /* --- Store the parameters --- */
522 mpkey(kd
, "q", dp
.q
, KCAT_SHARE
);
523 mpkey(kd
, "p", dp
.p
, KCAT_SHARE
);
524 mpkey(kd
, "g", dp
.g
, KCAT_SHARE
);
529 /* --- Store the seed for future verification --- */
534 base64_encode(&c
, ds
.p
, ds
.sz
, &d
);
535 base64_encode(&c
, 0, 0, &d
);
536 key_putattr(k
->kf
, k
->k
, "seed", d
.buf
);
538 dstr_putf(&d
, "%u", ds
.count
);
539 key_putattr(k
->kf
, k
->k
, "count", d
.buf
);
546 static void alg_dsa(keyopts
*k
)
551 key_data
*kd
= &k
->k
->k
;
553 /* --- Get the shared parameters --- */
560 /* --- Choose a private key --- */
562 x
= mprand_range(MP_NEWSEC
, q
, &rand_global
, 0);
563 mpmont_create(&mm
, p
);
564 y
= mpmont_exp(&mm
, MP_NEW
, g
, x
);
566 /* --- Store everything away --- */
568 mpkey(kd
, "y", y
, KCAT_PUB
);
570 kd
= key_structcreate(kd
, "private");
572 mpkey(kd
, "x", x
, KCAT_PRIV
| KF_BURN
);
573 dolock(k
, kd
, "private");
575 mp_drop(x
); mp_drop(y
);
578 static void alg_dhparam(keyopts
*k
)
580 static const char *pl
[] = { "p", "q", "g", 0 };
581 if (!copyparam(k
, pl
)) {
583 key_data
*kd
= &k
->k
->k
;
589 /* --- Choose a large safe prime number --- */
591 if (k
->f
& f_limlee
) {
596 rc
= dh_limlee(&dp
, k
->qbits
, k
->bits
,
597 (k
->f
& f_subgroup
) ? DH_SUBGROUP
: 0,
598 0, &rand_global
, (k
->f
& f_quiet
) ?
0 : pgen_ev
, 0,
599 (k
->f
& f_quiet
) ?
0 : pgen_evspin
, 0, &nf
, &f
);
603 for (i
= 0; i
< nf
; i
++) {
606 mp_writedstr(f
[i
], &d
, 10);
609 key_putattr(k
->kf
, k
->k
, "factors", d
.buf
);
613 rc
= dh_gen(&dp
, k
->qbits
, k
->bits
, 0, &rand_global
,
614 (k
->f
& f_quiet
) ?
0 : pgen_ev
, 0);
617 die(EXIT_FAILURE
, "Diffie-Hellman parameter generation failed");
620 mpkey(kd
, "p", dp
.p
, KCAT_SHARE
);
621 mpkey(kd
, "q", dp
.q
, KCAT_SHARE
);
622 mpkey(kd
, "g", dp
.g
, KCAT_SHARE
);
629 static void alg_dh(keyopts
*k
)
634 key_data
*kd
= &k
->k
->k
;
636 /* --- Get the shared parameters --- */
643 /* --- Choose a suitable private key --- *
645 * Since %$g$% has order %$q$%, choose %$x < q$%.
648 x
= mprand_range(MP_NEWSEC
, q
, &rand_global
, 0);
650 /* --- Compute the public key %$y = g^x \bmod p$% --- */
652 mpmont_create(&mm
, p
);
653 y
= mpmont_exp(&mm
, MP_NEW
, g
, x
);
656 /* --- Store everything away --- */
658 mpkey(kd
, "y", y
, KCAT_PUB
);
660 kd
= key_structcreate(kd
, "private");
662 mpkey(kd
, "x", x
, KCAT_PRIV
| KF_BURN
);
663 dolock(k
, kd
, "private");
665 mp_drop(x
); mp_drop(y
);
668 static void alg_bbs(keyopts
*k
)
673 /* --- Sanity checking --- */
676 die(EXIT_FAILURE
, "no shared parameters for Blum-Blum-Shub keys");
680 /* --- Generate the BBS parameters --- */
682 if (bbs_gen(&bp
, k
->bits
, &rand_global
, 0,
683 (k
->f
& f_quiet
) ?
0 : pgen_ev
, 0))
684 die(EXIT_FAILURE
, "Blum-Blum-Shub key generation failed");
686 /* --- Allrighty then --- */
690 mpkey(kd
, "n", bp
.n
, KCAT_PUB
);
692 kd
= key_structcreate(kd
, "private");
694 mpkey(kd
, "p", bp
.p
, KCAT_PRIV
| KF_BURN
);
695 mpkey(kd
, "q", bp
.q
, KCAT_PRIV
| KF_BURN
);
696 dolock(k
, kd
, "private");
701 static void alg_ecparam(keyopts
*k
)
703 static const char *pl
[] = { "curve", 0 };
704 if (!copyparam(k
, pl
)) {
707 key_data
*kd
= &k
->k
->k
;
709 /* --- Decide on a curve --- */
711 if (!k
->bits
) k
->bits
= 256;
713 if (k
->bits
<= 56) k
->curve
= "secp112r1";
714 else if (k
->bits
<= 64) k
->curve
= "secp128r1";
715 else if (k
->bits
<= 80) k
->curve
= "secp160r1";
716 else if (k
->bits
<= 96) k
->curve
= "secp192r1";
717 else if (k
->bits
<= 112) k
->curve
= "secp224r1";
718 else if (k
->bits
<= 128) k
->curve
= "secp256r1";
719 else if (k
->bits
<= 192) k
->curve
= "secp384r1";
720 else if (k
->bits
<= 256) k
->curve
= "secp521r1";
722 die(EXIT_FAILURE
, "no built-in curves provide %u-bit security",
726 /* --- Check it --- */
728 if ((e
= ec_getinfo(&ei
, k
->curve
)) != 0)
729 die(EXIT_FAILURE
, "error in curve spec: %s", e
);
730 if (!(k
->f
& f_quiet
) && (e
= ec_checkinfo(&ei
, &rand_global
)) != 0)
731 moan("WARNING! curve check failed: %s", e
);
734 /* --- Write out the answer --- */
737 kd
= key_structcreate(kd
, "curve");
738 key_string(kd
, k
->curve
);
743 static void alg_ec(keyopts
*k
)
745 key_data
*kd
= &k
->k
->k
;
752 /* --- Get the curve --- */
755 if ((kkd
= key_structfind(kd
, "curve")) == 0)
756 die(EXIT_FAILURE
, "unexpected failure looking up subkey `curve')");
757 if ((kkd
->e
& KF_ENCMASK
) != KENC_STRING
)
758 die(EXIT_FAILURE
, "subkey `curve' is not a string");
759 if ((e
= ec_getinfo(&ei
, kkd
->u
.p
)) != 0)
760 die(EXIT_FAILURE
, "error in curve spec: %s", e
);
762 /* --- Invent a private exponent and compute the public key --- */
764 x
= mprand_range(MP_NEWSEC
, ei
.r
, &rand_global
, 0);
765 ec_mul(ei
.c
, &p
, &ei
.g
, x
);
767 /* --- Store everything away --- */
769 kkd
= key_structcreate(kd
, "p");
772 kkd
= key_structcreate(kd
, "private");
774 mpkey(kkd
, "x", x
, KCAT_PRIV
| KF_BURN
);
782 /* --- The algorithm tables --- */
784 typedef struct keyalg
{
786 void (*proc
)(keyopts
*o
);
790 static keyalg algtab
[] = {
791 { "binary", alg_binary
, "Plain binary data" },
792 { "des", alg_des
, "Binary with DES-style parity" },
793 { "rsa", alg_rsa
, "RSA public-key encryption" },
794 { "dsa", alg_dsa
, "DSA digital signatures" },
795 { "dsa-param", alg_dsaparam
, "DSA shared parameters" },
796 { "dh", alg_dh
, "Diffie-Hellman key exchange" },
797 { "dh-param", alg_dhparam
, "Diffie-Hellman parameters" },
798 { "bbs", alg_bbs
, "Blum-Blum-Shub generator" },
799 { "ec-param", alg_ecparam
, "Elliptic curve parameters" },
800 { "ec", alg_ec
, "Elliptic curve crypto" },
804 /* --- @cmd_add@ --- */
806 static int cmd_add(int argc
, char *argv
[])
809 time_t exp
= KEXP_EXPIRE
;
810 const char *tag
= 0, *ptag
= 0;
812 keyalg
*alg
= algtab
;
813 const char *rtag
= 0;
814 keyopts k
= { 0, 0, DSTR_INIT
, 0, 0, 0, 0 };
816 /* --- Parse options for the subcommand --- */
819 static struct option opt
[] = {
820 { "algorithm", OPTF_ARGREQ
, 0, 'a' },
821 { "bits", OPTF_ARGREQ
, 0, 'b' },
822 { "qbits", OPTF_ARGREQ
, 0, 'B' },
823 { "parameters", OPTF_ARGREQ
, 0, 'p' },
824 { "expire", OPTF_ARGREQ
, 0, 'e' },
825 { "comment", OPTF_ARGREQ
, 0, 'c' },
826 { "tag", OPTF_ARGREQ
, 0, 't' },
827 { "rand-id", OPTF_ARGREQ
, 0, 'R' },
828 { "curve", OPTF_ARGREQ
, 0, 'C' },
829 { "lock", 0, 0, 'l' },
830 { "quiet", 0, 0, 'q' },
831 { "lim-lee", 0, 0, 'L' },
832 { "subgroup", 0, 0, 'S' },
835 int i
= mdwopt(argc
, argv
, "+a:b:B:p:e:c:t:R:C:lqrLS", opt
, 0, 0, 0);
839 /* --- Handle the various options --- */
843 /* --- Read an algorithm name --- */
847 size_t sz
= strlen(optarg
);
849 if (strcmp(optarg
, "list") == 0) {
850 for (a
= algtab
; a
->name
; a
++)
851 printf("%-10s %s\n", a
->name
, a
->help
);
856 for (a
= algtab
; a
->name
; a
++) {
857 if (strncmp(optarg
, a
->name
, sz
) == 0) {
858 if (a
->name
[sz
] == 0) {
862 die(EXIT_FAILURE
, "ambiguous algorithm name `%s'", optarg
);
868 die(EXIT_FAILURE
, "unknown algorithm name `%s'", optarg
);
871 /* --- Bits must be nonzero and a multiple of 8 --- */
875 k
.bits
= strtoul(optarg
, &p
, 0);
876 if (k
.bits
== 0 || *p
!= 0)
877 die(EXIT_FAILURE
, "bad bitlength `%s'", optarg
);
882 k
.qbits
= strtoul(optarg
, &p
, 0);
883 if (k
.qbits
== 0 || *p
!= 0)
884 die(EXIT_FAILURE
, "bad bitlength `%s'", optarg
);
887 /* --- Parameter selection --- */
893 /* --- Expiry dates get passed to @get_date@ for parsing --- */
896 if (strncmp(optarg
, "forever", strlen(optarg
)) == 0)
899 exp
= get_date(optarg
, 0);
901 die(EXIT_FAILURE
, "bad expiry date `%s'", optarg
);
905 /* --- Store comments without interpretation --- */
908 if (key_chkcomment(optarg
))
909 die(EXIT_FAILURE
, "bad comment string `%s'", optarg
);
913 /* --- Elliptic curve parameters --- */
916 if (strcmp(optarg
, "list") == 0) {
918 printf("Built-in elliptic curves:\n");
919 for (ee
= ectab
; ee
->name
; ee
++)
920 printf(" %s\n", ee
->name
);
926 /* --- Store tags --- */
929 if (key_chkident(optarg
))
930 die(EXIT_FAILURE
, "bad tag string `%s'", optarg
);
937 /* --- Other flags --- */
955 /* --- Other things are bogus --- */
963 /* --- Various sorts of bogosity --- */
965 if ((k
.f
& f_bogus
) || optind
+ 1 > argc
) {
967 "Usage: add [options] type [attr...]");
969 if (key_chkident(argv
[optind
]))
970 die(EXIT_FAILURE
, "bad key type `%s'", argv
[optind
]);
972 /* --- Set up various bits of the state --- */
974 if (exp
== KEXP_EXPIRE
)
975 exp
= time(0) + 14 * 24 * 60 * 60;
977 /* --- Open the file and create the basic key block --- *
979 * Keep on generating keyids until one of them doesn't collide.
982 doopen(&f
, KOPEN_WRITE
);
985 /* --- Key the generator --- */
990 uint32 id
= rand_global
.ops
->word(&rand_global
);
992 k
.k
= key_new(&f
, id
, argv
[optind
], exp
, &err
);
995 if (err
!= KERR_DUPID
)
996 die(EXIT_FAILURE
, "error adding new key: %s", key_strerror(err
));
999 /* --- Set various simple attributes --- */
1004 if (k
.f
& f_retag
) {
1005 if ((kk
= key_bytag(&f
, tag
)) != 0 && strcmp(kk
->tag
, tag
) == 0)
1006 key_settag(&f
, kk
, 0);
1008 if ((err
= key_settag(&f
, k
.k
, tag
)) != 0)
1009 die(EXIT_FAILURE
, "error setting key tag: %s", key_strerror(err
));
1013 int err
= key_setcomment(&f
, k
.k
, c
);
1015 die(EXIT_FAILURE
, "error setting key comment: %s", key_strerror(err
));
1018 setattr(&f
, k
.k
, argv
+ optind
+ 1);
1020 key_fulltag(k
.k
, &k
.tag
);
1022 /* --- Find the parameter key --- */
1025 if ((k
.p
= key_bytag(&f
, ptag
)) == 0)
1026 die(EXIT_FAILURE
, "parameter key `%s' not found", ptag
);
1027 if ((k
.p
->k
.e
& KF_ENCMASK
) != KENC_STRUCT
)
1028 die(EXIT_FAILURE
, "parameter key `%s' is not structured", ptag
);
1031 /* --- Now generate the actual key data --- */
1041 /*----- Key listing -------------------------------------------------------*/
1043 /* --- Listing options --- */
1045 typedef struct listopts
{
1046 const char *tfmt
; /* Date format (@strftime@-style) */
1047 int v
; /* Verbosity level */
1048 unsigned f
; /* Various flags */
1049 time_t t
; /* Time now (for key expiry) */
1050 key_filter kf
; /* Filter for matching keys */
1053 /* --- Listing flags --- */
1055 #define f_newline 2u /* Write newline before next entry */
1056 #define f_attr 4u /* Written at least one attribute */
1057 #define f_utc 8u /* Emit UTC time, not local time */
1059 /* --- @showkeydata@ --- *
1061 * Arguments: @key_data *k@ = pointer to key to write
1062 * @int ind@ = indentation level
1063 * @listopts *o@ = listing options
1064 * @dstr *d@ = tag string for this subkey
1068 * Use: Emits a piece of key data in a human-readable format.
1071 static void showkeydata(key_data
*k
, int ind
, listopts
*o
, dstr
*d
)
1073 #define INDENT(i) do { \
1075 for (_i = 0; _i < (i); _i++) { \
1080 switch (k
->e
& KF_ENCMASK
) {
1082 /* --- Binary key data --- *
1084 * Emit as a simple hex dump.
1088 const octet
*p
= k
->u
.k
.k
;
1089 const octet
*l
= p
+ k
->u
.k
.sz
;
1092 fputs(" {", stdout
);
1097 } else if (sz
% 8 == 0)
1101 printf("%02x", *p
++);
1106 fputs("}\n", stdout
);
1109 /* --- Encrypted data --- *
1111 * If the user is sufficiently keen, ask for a passphrase and decrypt the
1112 * key. Otherwise just say that it's encrypted and move on.
1117 fputs(" encrypted\n", stdout
);
1120 if (key_punlock(d
->buf
, k
, &kd
))
1121 printf(" <failed to unlock %s>\n", d
->buf
);
1123 fputs(" encrypted", stdout
);
1124 showkeydata(&kd
, ind
, o
, d
);
1130 /* --- Integer keys --- *
1132 * Emit as a large integer in decimal. This makes using the key in
1133 * `calc' or whatever easier.
1138 mp_writefile(k
->u
.m
, stdout
, 10);
1142 /* --- Strings --- */
1145 printf(" `%s'\n", k
->u
.p
);
1148 /* --- Elliptic curve points --- */
1151 fputs(" 0x", stdout
); mp_writefile(k
->u
.e
.x
, stdout
, 16);
1152 fputs(", 0x", stdout
); mp_writefile(k
->u
.e
.y
, stdout
, 16);
1156 /* --- Structured keys --- *
1158 * Just iterate over the subkeys.
1166 fputs(" {\n", stdout
);
1167 for (sym_mkiter(&i
, &k
->u
.s
); (ks
= sym_next(&i
)) != 0; ) {
1168 if (!key_match(&ks
->k
, &o
->kf
))
1171 printf("%s =", SYM_NAME(ks
));
1173 dstr_putf(d
, ".%s", SYM_NAME(ks
));
1174 showkeydata(&ks
->k
, ind
+ 2, o
, d
);
1177 fputs("}\n", stdout
);
1184 /* --- @showkey@ --- *
1186 * Arguments: @key *k@ = pointer to key to show
1187 * @listopts *o@ = pointer to listing options
1191 * Use: Emits a listing of a particular key.
1194 static void showkey(key
*k
, listopts
*o
)
1196 char ebuf
[24], dbuf
[24];
1199 /* --- Skip the key if the filter doesn't match --- */
1201 if (!key_match(&k
->k
, &o
->kf
))
1204 /* --- Sort out the expiry and deletion times --- */
1206 if (KEY_EXPIRED(o
->t
, k
->exp
))
1207 strcpy(ebuf
, "expired");
1208 else if (k
->exp
== KEXP_FOREVER
)
1209 strcpy(ebuf
, "forever");
1211 tm
= (o
->f
& f_utc
) ?
gmtime(&k
->exp
) : localtime(&k
->exp
);
1212 strftime(ebuf
, sizeof(ebuf
), o
->tfmt
, tm
);
1215 if (KEY_EXPIRED(o
->t
, k
->del
))
1216 strcpy(dbuf
, "deleted");
1217 else if (k
->del
== KEXP_FOREVER
)
1218 strcpy(dbuf
, "forever");
1220 tm
= (o
->f
& f_utc
) ?
gmtime(&k
->del
) : localtime(&k
->del
);
1221 strftime(dbuf
, sizeof(dbuf
), o
->tfmt
, tm
);
1224 /* --- If in compact format, just display and quit --- */
1227 if (!(o
->f
& f_newline
)) {
1228 printf("%8s %-20s %-20s %-10s %-10s\n",
1229 "Id", "Tag", "Type", "Expire", "Delete");
1231 printf("%08lx %-20s %-20s %-10s %-10s\n",
1232 (unsigned long)k
->id
, k
->tag ? k
->tag
: "<none>",
1233 k
->type
, ebuf
, dbuf
);
1238 /* --- Display the standard header --- */
1240 if (o
->f
& f_newline
)
1241 fputc('\n', stdout
);
1242 printf("keyid: %08lx\n", (unsigned long)k
->id
);
1243 printf("tag: %s\n", k
->tag ? k
->tag
: "<none>");
1244 printf("type: %s\n", k
->type
);
1245 printf("expiry: %s\n", ebuf
);
1246 printf("delete: %s\n", dbuf
);
1247 printf("comment: %s\n", k
->c ? k
->c
: "<none>");
1249 /* --- Display the attributes --- */
1253 const char *av
, *an
;
1256 printf("attributes:");
1257 for (key_mkattriter(&i
, k
); key_nextattr(&i
, &an
, &av
); ) {
1258 printf("\n %s = %s", an
, av
);
1262 fputc('\n', stdout
);
1267 /* --- If dumping requested, dump the raw key data --- */
1271 fputs("key:", stdout
);
1273 showkeydata(&k
->k
, 0, o
, &d
);
1280 /* --- @cmd_list@ --- */
1282 static int cmd_list(int argc
, char *argv
[])
1286 listopts o
= { 0, 0, 0, 0, { 0, 0 } };
1288 /* --- Parse subcommand options --- */
1291 static struct option opt
[] = {
1292 { "quiet", 0, 0, 'q' },
1293 { "verbose", 0, 0, 'v' },
1294 { "utc", 0, 0, 'u' },
1295 { "filter", OPTF_ARGREQ
, 0, 'f' },
1298 int i
= mdwopt(argc
, argv
, "+uqvf:", opt
, 0, 0, 0);
1315 int e
= key_readflags(optarg
, &p
, &o
.kf
.f
, &o
.kf
.m
);
1317 die(EXIT_FAILURE
, "bad filter string `%s'", optarg
);
1326 die(EXIT_FAILURE
, "Usage: list [-uqv] [-f filter] [tag...]");
1328 /* --- Open the key file --- */
1330 doopen(&f
, KOPEN_READ
);
1333 /* --- Set up the time format --- */
1336 o
.tfmt
= "%Y-%m-%d";
1337 else if (o
.f
& f_utc
)
1338 o
.tfmt
= "%Y-%m-%d %H:%M:%S UTC";
1340 o
.tfmt
= "%Y-%m-%d %H:%M:%S %Z";
1342 /* --- If specific keys were requested use them, otherwise do all --- *
1344 * Some day, this might turn into a wildcard match.
1347 if (optind
< argc
) {
1349 if ((k
= key_bytag(&f
, argv
[optind
])) != 0)
1352 moan("key `%s' not found", argv
[optind
]);
1356 } while (optind
< argc
);
1359 for (key_mkiter(&i
, &f
); (k
= key_next(&i
)) != 0; )
1367 return (EXIT_FAILURE
);
1372 /*----- Command implementation --------------------------------------------*/
1374 /* --- @cmd_expire@ --- */
1376 static int cmd_expire(int argc
, char *argv
[])
1384 die(EXIT_FAILURE
, "Usage: expire tag...");
1385 doopen(&f
, KOPEN_WRITE
);
1386 for (i
= 1; i
< argc
; i
++) {
1387 if ((k
= key_bytag(&f
, argv
[i
])) != 0)
1390 moan("key `%s' not found", argv
[i
]);
1398 /* --- @cmd_delete@ --- */
1400 static int cmd_delete(int argc
, char *argv
[])
1408 die(EXIT_FAILURE
, "Usage: delete tag...");
1409 doopen(&f
, KOPEN_WRITE
);
1410 for (i
= 1; i
< argc
; i
++) {
1411 if ((k
= key_bytag(&f
, argv
[i
])) != 0)
1414 moan("key `%s' not found", argv
[i
]);
1422 /* --- @cmd_setattr@ --- */
1424 static int cmd_setattr(int argc
, char *argv
[])
1430 die(EXIT_FAILURE
, "Usage: setattr tag attr...");
1431 doopen(&f
, KOPEN_WRITE
);
1432 if ((k
= key_bytag(&f
, argv
[1])) == 0)
1433 die(EXIT_FAILURE
, "key `%s' not found", argv
[1]);
1434 setattr(&f
, k
, argv
+ 2);
1439 /* --- @cmd_finger@ --- */
1441 static void fingerprint(key
*k
, const key_filter
*kf
)
1444 octet hash
[RMD160_HASHSZ
];
1448 if (!key_encode(&k
->k
, &d
, kf
))
1451 rmd160_hash(&r
, d
.buf
, d
.len
);
1452 rmd160_done(&r
, hash
);
1456 for (i
= 0; i
< sizeof(hash
); i
++) {
1457 if (i
&& i
% 4 == 0)
1459 printf("%02x", hash
[i
]);
1461 printf(" %s\n", d
.buf
);
1465 static int cmd_finger(int argc
, char *argv
[])
1469 key_filter kf
= { KF_NONSECRET
, KF_NONSECRET
};
1472 static struct option opt
[] = {
1473 { "filter", OPTF_ARGREQ
, 0, 'f' },
1476 int i
= mdwopt(argc
, argv
, "+f:", opt
, 0, 0, 0);
1482 int err
= key_readflags(optarg
, &p
, &kf
.f
, &kf
.m
);
1484 die(EXIT_FAILURE
, "bad filter string `%s'", optarg
);
1492 argv
+= optind
; argc
-= optind
;
1494 die(EXIT_FAILURE
, "Usage: fingerprint [-f filter] [tag...]");
1496 doopen(&f
, KOPEN_READ
);
1500 for (i
= 0; i
< argc
; i
++) {
1501 key
*k
= key_bytag(&f
, argv
[i
]);
1503 fingerprint(k
, &kf
);
1506 moan("key `%s' not found", argv
[i
]);
1512 for (key_mkiter(&i
, &f
); (k
= key_next(&i
)) != 0; )
1513 fingerprint(k
, &kf
);
1518 /* --- @cmd_comment@ --- */
1520 static int cmd_comment(int argc
, char *argv
[])
1526 if (argc
< 2 || argc
> 3)
1527 die(EXIT_FAILURE
, "Usage: comment tag [comment]");
1528 doopen(&f
, KOPEN_WRITE
);
1529 if ((k
= key_bytag(&f
, argv
[1])) == 0)
1530 die(EXIT_FAILURE
, "key `%s' not found", argv
[1]);
1531 if ((err
= key_setcomment(&f
, k
, argv
[2])) != 0)
1532 die(EXIT_FAILURE
, "bad comment `%s': %s", argv
[2], key_strerror(err
));
1537 /* --- @cmd_tag@ --- */
1539 static int cmd_tag(int argc
, char *argv
[])
1548 static struct option opt
[] = {
1549 { "retag", 0, 0, 'r' },
1552 int i
= mdwopt(argc
, argv
, "+r", opt
, 0, 0, 0);
1565 argv
+= optind
; argc
-= optind
;
1566 if (argc
< 1 || argc
> 2 || rc
)
1567 die(EXIT_FAILURE
, "Usage: tag [-r] tag [new-tag]");
1568 doopen(&f
, KOPEN_WRITE
);
1569 if (flags
& f_retag
) {
1570 if ((k
= key_bytag(&f
, argv
[1])) != 0 && strcmp(k
->tag
, argv
[1]) == 0)
1571 key_settag(&f
, k
, 0);
1573 if ((k
= key_bytag(&f
, argv
[0])) == 0)
1574 die(EXIT_FAILURE
, "key `%s' not found", argv
[0]);
1575 if ((err
= key_settag(&f
, k
, argv
[1])) != 0)
1576 die(EXIT_FAILURE
, "bad tag `%s': %s", argv
[1], key_strerror(err
));
1581 /* --- @cmd_lock@ --- */
1583 static int cmd_lock(int argc
, char *argv
[])
1591 die(EXIT_FAILURE
, "Usage: lock qtag");
1592 doopen(&f
, KOPEN_WRITE
);
1593 if (key_qtag(&f
, argv
[1], &d
, &k
, &kd
))
1594 die(EXIT_FAILURE
, "key `%s' not found", argv
[1]);
1595 if (kd
->e
== KENC_ENCRYPT
&& key_punlock(d
.buf
, kd
, kd
))
1596 die(EXIT_FAILURE
, "couldn't unlock key `%s'", d
.buf
);
1597 if (key_plock(d
.buf
, kd
, kd
))
1598 die(EXIT_FAILURE
, "failed to lock key `%s'", d
.buf
);
1604 /* --- @cmd_unlock@ --- */
1606 static int cmd_unlock(int argc
, char *argv
[])
1614 die(EXIT_FAILURE
, "Usage: unlock qtag");
1615 doopen(&f
, KOPEN_WRITE
);
1616 if (key_qtag(&f
, argv
[1], &d
, &k
, &kd
))
1617 die(EXIT_FAILURE
, "key `%s' not found", argv
[1]);
1618 if (kd
->e
!= KENC_ENCRYPT
)
1619 die(EXIT_FAILURE
, "key `%s' is not encrypted", d
.buf
);
1620 if (kd
->e
== KENC_ENCRYPT
&& key_punlock(d
.buf
, kd
, kd
))
1621 die(EXIT_FAILURE
, "couldn't unlock key `%s'", d
.buf
);
1627 /* --- @cmd_extract@ --- */
1629 static int cmd_extract(int argc
, char *argv
[])
1635 key_filter kf
= { 0, 0 };
1639 static struct option opt
[] = {
1640 { "filter", OPTF_ARGREQ
, 0, 'f' },
1643 int i
= mdwopt(argc
, argv
, "f:", opt
, 0, 0, 0);
1649 int err
= key_readflags(optarg
, &p
, &kf
.f
, &kf
.m
);
1651 die(EXIT_FAILURE
, "bad filter string `%s'", optarg
);
1659 argv
+= optind
; argc
-= optind
;
1661 die(EXIT_FAILURE
, "Usage: extract [-f filter] file [tag...]");
1662 if (strcmp(*argv
, "-") == 0)
1664 else if (!(fp
= fopen(*argv
, "w"))) {
1665 die(EXIT_FAILURE
, "couldn't open `%s' for writing: %s",
1666 *argv
, strerror(errno
));
1669 doopen(&f
, KOPEN_READ
);
1673 for (key_mkiter(&i
, &f
); (k
= key_next(&i
)) != 0; )
1674 key_extract(&f
, k
, fp
, &kf
);
1676 for (i
= 1; i
< argc
; i
++) {
1677 if ((k
= key_bytag(&f
, argv
[i
])) != 0)
1678 key_extract(&f
, k
, fp
, &kf
);
1680 moan("key `%s' not found", argv
[i
]);
1686 die(EXIT_FAILURE
, "error writing file: %s", strerror(errno
));
1691 /* --- @cmd_tidy@ --- */
1693 static int cmd_tidy(int argc
, char *argv
[])
1697 die(EXIT_FAILURE
, "usage: tidy");
1698 doopen(&f
, KOPEN_WRITE
);
1699 f
.f
|= KF_MODIFIED
; /* Nasty hack */
1704 /* --- @cmd_merge@ --- */
1706 static int cmd_merge(int argc
, char *argv
[])
1712 die(EXIT_FAILURE
, "Usage: merge file");
1713 if (strcmp(argv
[1], "-") == 0)
1715 else if (!(fp
= fopen(argv
[1], "r"))) {
1716 die(EXIT_FAILURE
, "couldn't open `%s' for writing: %s",
1717 argv
[1], strerror(errno
));
1720 doopen(&f
, KOPEN_WRITE
);
1721 key_merge(&f
, argv
[1], fp
, key_moan
, 0);
1726 /*----- Main command table ------------------------------------------------*/
1730 int (*cmd
)(int /*argc*/, char */
*argv*/
[]);
1735 "add [options] type [attr...]\n\
1736 Options: [-lqrLS] [-a alg] [-bB bits] [-p param] [-R tag]\n\
1737 [-e expire] [-t tag] [-c comment]", "\
1740 -a, --algorithm=ALG Generate keys suitable for ALG.\n\
1741 -b, --bits=N Generate an N-bit key.\n\
1742 -B, --qbits=N Use an N-bit subgroup or factors.\n\
1743 -p, --parameters=TAG Get group parameters from TAG.\n\
1744 -C, --curve=CURVE Use elliptic curve CURVE.\n\
1745 -e, --expire=TIME Make the key expire after TIME.\n\
1746 -c, --comment=STRING Attach the command STRING to the key.\n\
1747 -t, --tag=TAG Tag the key with the name TAG.\n\
1748 -r, --retag Untag any key currently with that tag.\n\
1749 -R, --rand-id=TAG Use key named TAG for the random number generator.\n\
1750 -l, --lock Lock the generated key with a passphrase.\n\
1751 -q, --quiet Don't give progress indicators while working.\n\
1752 -L, --lim-lee Generate Lim-Lee primes for Diffie-Hellman groups.\n\
1753 -S, --subgroup Use a prime-order subgroup for Diffie-Hellman.\n\
1755 { "expire", cmd_expire
, "expire tag..." },
1756 { "delete", cmd_delete
, "delete tag..." },
1757 { "tag", cmd_tag
, "tag [-r] tag [new-tag]", "\
1760 -r, --retag Untag any key currently called new-tag.\n\
1762 { "setattr", cmd_setattr
, "setattr tag attr..." },
1763 { "comment", cmd_comment
, "comment tag [comment]" },
1764 { "lock", cmd_lock
, "lock qtag" },
1765 { "unlock", cmd_unlock
, "unlock qtag" },
1766 { "list", cmd_list
, "list [-uqv] [-f filter] [tag...]", "\
1769 -u, --utc Display expiry times etc. in UTC, not local time.\n\
1770 -q, --quiet Show less information.\n\
1771 -v, --verbose Show more information.\n\
1773 { "fingerprint", cmd_finger
, "fingerprint [-f filter] [tag...]", "\
1776 -f, --filter=FILT Only hash key components matching FILT.\n\
1778 { "tidy", cmd_tidy
, "tidy" },
1779 { "extract", cmd_extract
, "extract [-f filter] file [tag...]", "\
1782 -f, --filter=FILT Only extract key components matching FILT.\n\
1784 { "merge", cmd_merge
, "merge file" },
1788 typedef struct cmd cmd
;
1790 /*----- Main code ---------------------------------------------------------*/
1792 /* --- @findcmd@ --- *
1794 * Arguments: @const char *name@ = a command name
1796 * Returns: Pointer to the command structure.
1798 * Use: Looks up a command by name. If the command isn't found, an
1799 * error is reported and the program is terminated.
1802 static cmd
*findcmd(const char *name
)
1804 cmd
*c
, *chosen
= 0;
1805 size_t sz
= strlen(name
);
1807 for (c
= cmds
; c
->name
; c
++) {
1808 if (strncmp(name
, c
->name
, sz
) == 0) {
1809 if (c
->name
[sz
] == 0) {
1813 die(EXIT_FAILURE
, "ambiguous command name `%s'", name
);
1819 die(EXIT_FAILURE
, "unknown command name `%s'", name
);
1823 /* --- Helpful GNUy functions --- */
1825 void usage(FILE *fp
)
1827 pquis(fp
, "Usage: $ [-k keyring] command [args]\n");
1830 void version(FILE *fp
)
1832 pquis(fp
, "$, Catacomb version " VERSION
"\n");
1835 void help(FILE *fp
, char **argv
)
1843 fprintf(fp
, "Usage: %s [-k keyring] %s\n", QUIS
, c
->usage
);
1851 Performs various simple key management operations. Command line options\n\
1854 -h, --help [COMMAND] Display this help text (or help for COMMAND).\n\
1855 -v, --version Display version number.\n\
1856 -u, --usage Display short usage summary.\n\
1858 -k, --keyring=FILE Read and write keys in FILE.\n\
1859 -i, --id=TAG Use key TAG for random number generator.\n\
1860 -t, --type=TYPE Use key TYPE for random number generator.\n\
1862 The following commands are understood:\n\n",
1864 for (c
= cmds
; c
->name
; c
++)
1865 fprintf(fp
, "%s\n", c
->usage
);
1871 * Arguments: @int argc@ = number of command line arguments
1872 * @char *argv[]@ = array of command line arguments
1874 * Returns: Nonzero on failure.
1876 * Use: Main program. Performs simple key management functions.
1879 int main(int argc
, char *argv
[])
1885 /* --- Initialization --- */
1890 /* --- Parse command line options --- */
1893 static struct option opt
[] = {
1895 /* --- Standard GNUy help options --- */
1897 { "help", 0, 0, 'h' },
1898 { "version", 0, 0, 'v' },
1899 { "usage", 0, 0, 'u' },
1901 /* --- Real live useful options --- */
1903 { "keyring", OPTF_ARGREQ
, 0, 'k' },
1905 /* --- Magic terminator --- */
1909 int i
= mdwopt(argc
, argv
, "+hvu k:", opt
, 0, 0, 0);
1915 /* --- GNU help options --- */
1918 help(stdout
, argv
+ optind
);
1927 /* --- Real useful options --- */
1933 /* --- Bogosity --- */
1941 /* --- Complain about excessive bogons --- */
1943 if (f
& f_bogus
|| optind
== argc
) {
1948 /* --- Initialize the Catacomb random number generator --- */
1950 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
1951 rand_seed(RAND_GLOBAL
, 160);
1953 /* --- Dispatch to appropriate command handler --- */
1958 return (findcmd(argv
[0])->cmd(argc
, argv
));
1961 /*----- That's all, folks -------------------------------------------------*/