5 * Command-line encryption tool
7 * (c) 2004 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 /*----- Header files ------------------------------------------------------*/
39 #include <mLib/base64.h>
40 #include <mLib/dstr.h>
41 #include <mLib/mdwopt.h>
42 #include <mLib/quis.h>
43 #include <mLib/report.h>
56 /*----- Utilities ---------------------------------------------------------*/
58 /* --- @keyreport@ --- *
60 * Arguments: @const char *file@ = filename containing the error
61 * @int line@ = line number in file
62 * @const char *err@ = error text message
63 * @void *p@ = unimportant pointer
67 * Use: Reports errors during the opening of a key file.
70 static void keyreport(const char *file
, int line
, const char *err
, void *p
)
72 moan("error in keyring `%s' at line `%s': %s", file
, line
, err
);
75 /*----- Static variables --------------------------------------------------*/
77 static const char *keyring
= "keyring";
79 /*----- Data format -------------------------------------------------------*/
83 * The encrypted message is divided into chunks, each preceded by a two-octet
84 * length. The chunks don't need to be large -- the idea is that we can
85 * stream the chunks in and out.
87 * The first chunk is a header. It contains the decryption key-id, and maybe
88 * the verification key-id if the message is signed.
90 * Next comes the key-encapsulation chunk. This is decrypted in some
91 * KEM-specific way to yield a secret hash. The hash is expanded using an
92 * MGF (or similar) to make a symmetric encryption and MAC key.
94 * If the message is signed, there comes a signature chunk. The signature is
95 * on the further output of the MGF. This means that the recipient can
96 * modify the message and still have a valid signature, so it's not useful
97 * for proving things to other people; but it also means that the recipient
98 * knows that the message is from someone who knows the hash, which limits
99 * the possiblities to (a) whoever encrypted the message (good!) and (b)
100 * whoever knows the recipient's private key.
102 * Then come message chunks. Each one begins with a MAC over an implicit
103 * sequence number and the ciphertext. The final chunk's ciphertext is
104 * empty; no other chunk is empty. Thus can the correct end-of-file be
108 /*----- Chunk I/O ---------------------------------------------------------*/
110 static void chunk_write(enc
*e
, buf
*b
)
116 if (e
->ops
->write(e
, l
, 2) ||
117 e
->ops
->write(e
, BBASE(b
), BLEN(b
)))
118 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
121 static void chunk_read(enc
*e
, dstr
*d
, buf
*b
)
128 if (e
->ops
->read(e
, l
, 2) != 2)
132 if (e
->ops
->read(e
, d
->buf
, n
) != n
)
135 buf_init(b
, d
->buf
, d
->len
);
139 if (!errno
) die(EXIT_FAILURE
, "unexpected end-of-file on input");
140 else die(EXIT_FAILURE
, "error reading input: %s", strerror(errno
));
143 /*----- Encryption --------------------------------------------------------*/
145 static int encrypt(int argc
, char *argv
[])
147 const char *of
= 0, *kn
= "ccrypt", *skn
= 0;
150 const char *ef
= "binary";
175 static const struct option opt
[] = {
176 { "key", OPTF_ARGREQ
, 0, 'k' },
177 { "sign-key", OPTF_ARGREQ
, 0, 's' },
178 { "armour", 0, 0, 'a' },
179 { "armor", 0, 0, 'a' },
180 { "format", OPTF_ARGREQ
, 0, 'f' },
181 { "output", OPTF_ARGREQ
, 0, 'o' },
184 i
= mdwopt(argc
, argv
, "k:s:af:o:", opt
, 0, 0, 0);
187 case 'k': kn
= optarg
; break;
188 case 's': skn
= optarg
; break;
189 case 'a': ef
= "pem"; break;
190 case 'f': ef
= optarg
; break;
191 case 'o': of
= optarg
; break;
192 default: f
|= f_bogus
; break;
195 if (argc
- optind
> 1 || (f
& f_bogus
))
196 die(EXIT_FAILURE
, "Usage: encrypt [-OPTIONS] [FILE]");
198 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
199 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
200 if ((k
= key_bytag(&kf
, kn
)) == 0)
201 die(EXIT_FAILURE
, "key `%s' not found", kn
);
202 if (skn
&& (sk
= key_bytag(&kf
, skn
)) == 0)
203 die(EXIT_FAILURE
, "key `%s' not found", skn
);
205 if ((eo
= getenc(ef
)) == 0)
206 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
210 else if (strcmp(argv
[optind
], "-") == 0) {
213 } else if ((fp
= fopen(argv
[optind
], "rb")) == 0) {
214 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
215 argv
[optind
], strerror(errno
));
219 if (!of
|| strcmp(of
, "-") == 0)
221 else if ((ofp
= fopen(of
, eo
->wmode
)) == 0) {
222 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
223 ofp
, strerror(errno
));
228 e
= initenc(eo
, ofp
, "CATCRYPT ENCRYPTED MESSAGE", 1);
229 km
= getkem(k
, "cckem", 0);
230 if ((err
= km
->ops
->check(km
)) != 0)
231 moan("key `%s' fails check: %s", d
.buf
, err
);
235 s
= getsig(sk
, "ccsig", 1);
236 if ((err
= s
->ops
->check(s
)) != 0)
237 moan("key `%s' fails check: %s", d
.buf
, err
);
240 /* --- Build the header chunk --- */
243 dstr_ensure(&d
, 256);
244 buf_init(&b
, d
.buf
, 256);
245 buf_putu32(&b
, k
->id
);
246 if (sk
) buf_putu32(&b
, sk
->id
);
250 /* --- Build the KEM chunk --- */
253 if (setupkem(km
, &d
, &cx
, &c
, &m
))
254 die(EXIT_FAILURE
, "failed to encapsulate key");
255 buf_init(&b
, d
.buf
, d
.len
);
259 /* --- Write the signature chunk --- */
262 GC_ENCRYPT(cx
, 0, bb
, 1024);
263 GH_HASH(s
->h
, bb
, 1024);
265 if ((en
= s
->ops
->doit(s
, &d
)) != 0)
266 die(EXIT_FAILURE
, "error creating signature: %s", key_strerror(en
));
267 buf_init(&b
, d
.buf
, d
.len
);
272 /* --- Now do the main crypto --- */
274 assert(GC_CLASS(c
)->blksz
<= sizeof(bb
));
275 dstr_ensure(&d
, sizeof(bb
) + GM_CLASS(m
)->hashsz
);
282 if (GC_CLASS(c
)->blksz
) {
283 GC_ENCRYPT(cx
, 0, bb
, GC_CLASS(c
)->blksz
);
286 n
= fread(bb
, 1, sizeof(bb
), fp
);
288 buf_init(&b
, d
.buf
, d
.sz
);
289 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
291 assert(tag
); assert(ct
);
292 GC_ENCRYPT(c
, bb
, ct
, n
);
299 /* --- Final terminator packet --- */
301 buf_init(&b
, d
.buf
, d
.sz
);
302 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
308 /* --- All done --- */
325 /*---- Decryption ---------------------------------------------------------*/
327 static int decrypt(int argc
, char *argv
[])
332 const char *ef
= "binary";
357 static const struct option opt
[] = {
358 { "armour", 0, 0, 'a' },
359 { "armor", 0, 0, 'a' },
360 { "verbose", 0, 0, 'v' },
361 { "quiet", 0, 0, 'q' },
362 { "format", OPTF_ARGREQ
, 0, 'f' },
363 { "output", OPTF_ARGREQ
, 0, 'o' },
366 i
= mdwopt(argc
, argv
, "af:o:qv", opt
, 0, 0, 0);
369 case 'a': ef
= "pem"; break;
370 case 'v': verb
++; break;
371 case 'q': if (verb
) verb
--; break;
372 case 'f': ef
= optarg
; break;
373 case 'o': of
= optarg
; break;
374 default: f
|= f_bogus
; break;
377 if (argc
- optind
> 1 || (f
& f_bogus
))
378 die(EXIT_FAILURE
, "Usage: decrypt [-OPTIONS] [FILE]");
380 if ((eo
= getenc(ef
)) == 0)
381 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
385 else if (strcmp(argv
[optind
], "-") == 0) {
388 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
389 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
390 argv
[optind
], strerror(errno
));
394 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
395 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
397 e
= initenc(eo
, fp
, "CATCRYPT ENCRYPTED MESSAGE", 0);
399 /* --- Read the header chunk --- */
401 chunk_read(e
, &d
, &b
);
402 if (buf_getu32(&b
, &id
)) {
403 if (verb
) printf("FAIL malformed header: missing keyid\n");
406 if ((k
= key_byid(&kf
, id
)) == 0) {
407 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
411 if (buf_getu32(&b
, &id
)) {
412 if (verb
) printf("FAIL malformed header: missing signature keyid\n");
415 if ((sk
= key_byid(&kf
, id
)) == 0) {
416 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
421 if (verb
) printf("FAIL malformed header: junk at end\n");
425 /* --- Find the key --- */
427 km
= getkem(k
, "cckem", 1);
429 /* --- Read the KEM chunk --- */
431 chunk_read(e
, &d
, &b
);
432 if (setupkem(km
, &d
, &cx
, &c
, &m
)) {
433 if (verb
) printf("FAIL failed to decapsulate key\n");
437 /* --- Verify the signature, if there is one --- */
440 s
= getsig(sk
, "ccsig", 0);
443 if (verb
&& (err
= s
->ops
->check(s
)) != 0)
444 printf("WARN verification key %s fails check: %s\n", d
.buf
, err
);
446 dstr_ensure(&d
, 1024);
447 GC_ENCRYPT(cx
, 0, d
.buf
, 1024);
448 GH_HASH(s
->h
, d
.buf
, 1024);
449 chunk_read(e
, &d
, &b
);
450 if (s
->ops
->doit(s
, &d
)) {
451 if (verb
) printf("FAIL signature verification failed\n");
457 printf("INFO good signature from %s\n", d
.buf
);
460 printf("INFO no signature packet\n");
462 /* --- Now decrypt the main body --- */
464 if (!of
|| strcmp(of
, "-") == 0) {
466 if (verb
) printf("DATA\n");
467 } else if ((ofp
= fopen(of
, "wb")) == 0) {
468 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
469 ofp
, strerror(errno
));
473 dstr_ensure(&d
, GC_CLASS(c
)->blksz
);
476 if (GC_CLASS(c
)->blksz
) {
477 GC_ENCRYPT(cx
, 0, d
.buf
, GC_CLASS(c
)->blksz
);
482 GH_HASH(h
, d
.buf
, 4);
484 chunk_read(e
, &d
, &b
);
485 if ((tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
)) == 0) {
486 if (verb
) printf("%sFAIL bad ciphertext chunk: no tag\n",
487 ofp
== stdout ?
"\n" : "");
490 GH_HASH(h
, BCUR(&b
), BLEFT(&b
));
491 if (memcmp(tag
, GH_DONE(h
, 0), GM_CLASS(m
)->hashsz
) != 0) {
493 printf("%sFAIL bad ciphertext chunk: authentication failure\n",
494 ofp
== stdout ?
"\n" : "");
499 GC_DECRYPT(c
, BCUR(&b
), BCUR(&b
), BLEFT(&b
));
500 if (fwrite(BCUR(&b
), 1, BLEFT(&b
), ofp
) != BLEFT(&b
)) {
501 if (verb
) printf("%sFAIL error writing output: %s\n",
502 ofp
== stdout ?
"\n" : "", strerror(errno
));
507 if (fflush(ofp
) || ferror(ofp
)) {
508 if (verb
) printf("%sFAIL error writing output: %s\n",
509 ofp
== stdout ?
"\n" : "", strerror(errno
));
514 if (verb
&& ofp
!= stdout
)
515 printf("OK decrypted successfully\n");
529 /*----- Test code ---------------------------------------------------------*/
531 static int encode(int argc
, char *argv
[])
536 const char *ef
= "binary";
537 const char *bd
= "MESSAGE";
548 static const struct option opt
[] = {
549 { "format", OPTF_ARGREQ
, 0, 'f' },
550 { "boundary", OPTF_ARGREQ
, 0, 'b' },
551 { "output", OPTF_ARGREQ
, 0, 'o' },
554 i
= mdwopt(argc
, argv
, "f:b:o:", opt
, 0, 0, 0);
557 case 'f': ef
= optarg
; break;
558 case 'b': bd
= optarg
; break;
559 case 'o': of
= optarg
; break;
560 default: f
|= f_bogus
; break;
563 if (argc
- optind
> 1 || (f
& f_bogus
))
564 die(EXIT_FAILURE
, "Usage: encode [-OPTIONS] [FILE]");
566 if ((eo
= getenc(ef
)) == 0)
567 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
571 else if (strcmp(argv
[optind
], "-") == 0) {
574 } else if ((fp
= fopen(argv
[optind
], "rb")) == 0) {
575 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
576 argv
[optind
], strerror(errno
));
580 if (!of
|| strcmp(of
, "-") == 0)
582 else if ((ofp
= fopen(of
, eo
->wmode
)) == 0) {
583 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
584 ofp
, strerror(errno
));
587 e
= initenc(eo
, ofp
, bd
, 1);
590 n
= fread(buf
, 1, sizeof(buf
), fp
);
591 if (e
->ops
->write(e
, buf
, n
))
592 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
593 } while (n
== sizeof(buf
));
601 static int decode(int argc
, char *argv
[])
606 const char *ef
= "binary";
617 static const struct option opt
[] = {
618 { "format", OPTF_ARGREQ
, 0, 'f' },
619 { "boundary", OPTF_ARGREQ
, 0, 'b' },
620 { "output", OPTF_ARGREQ
, 0, 'o' },
623 i
= mdwopt(argc
, argv
, "f:b:o:", opt
, 0, 0, 0);
626 case 'f': ef
= optarg
; break;
627 case 'b': bd
= optarg
; break;
628 case 'o': of
= optarg
; break;
629 default: f
|= f_bogus
; break;
632 if (argc
- optind
> 1 || (f
& f_bogus
))
633 die(EXIT_FAILURE
, "Usage: decode [-OPTIONS] [FILE]");
635 if ((eo
= getenc(ef
)) == 0)
636 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
640 else if (strcmp(argv
[optind
], "-") == 0) {
643 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
644 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
645 argv
[optind
], strerror(errno
));
649 if (!of
|| strcmp(of
, "-") == 0)
651 else if ((ofp
= fopen(of
, "wb")) == 0) {
652 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
653 ofp
, strerror(errno
));
656 e
= initenc(eo
, fp
, bd
, 0);
659 if ((i
= e
->ops
->read(e
, buf
, sizeof(buf
))) < 0)
660 die(EXIT_FAILURE
, "error reading input: %s", strerror(errno
));
661 if (fwrite(buf
, 1, i
, ofp
) < i
)
662 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
663 } while (i
== sizeof(buf
));
671 /*----- Main code ---------------------------------------------------------*/
675 listtab[i].name, listtab[i].name) \
676 LI("Key-encapsulation mechanisms", kem, \
677 kemtab[i].name, kemtab[i].name) \
678 LI("Signature schemes", sig, \
679 sigtab[i].name, sigtab[i].name) \
680 LI("Encodings", enc, \
681 enctab[i].name, enctab[i].name) \
682 LI("Symmetric encryption algorithms", cipher, \
683 gciphertab[i], gciphertab[i]->name) \
684 LI("Hash functions", hash, \
685 ghashtab[i], ghashtab[i]->name) \
686 LI("Message authentication codes", mac, \
687 gmactab[i], gmactab[i]->name)
689 MAKELISTTAB(listtab
, LISTS
)
691 int cmd_show(int argc
, char *argv
[])
693 return (displaylists(listtab
, argv
+ 1));
696 static int cmd_help(int, char **);
698 static cmd cmdtab
[] = {
699 { "help", cmd_help
, "help [COMMAND...]" },
700 { "show", cmd_show
, "show [ITEM...]" },
702 "encode [-f FORMAT] [-b LABEL] [-o OUTPUT] [FILE]",
706 -f, --format=FORMAT Encode to FORMAT.\n\
707 -b, --boundary=LABEL PEM boundary is LABEL.\n\
708 -o, --output=FILE Write output to FILE.\n\
711 "decode [-f FORMAT] [-b LABEL] [-o OUTPUT] [FILE]",
715 -f, --format=FORMAT Decode from FORMAT.\n\
716 -b, --boundary=LABEL PEM boundary is LABEL.\n\
717 -o, --output=FILE Write output to FILE.\n\
719 { "encrypt", encrypt
,
720 "encrypt [-a] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
721 [-o OUTPUT] [FILE]", "\
724 -a, --armour Same as `-f pem'.\n\
725 -f, --format=FORMAT Encode as FORMAT.\n\
726 -k, --key=TAG Use public encryption key named by TAG.\n\
727 -s, --sign-key=TAG Use private signature key named by TAG.\n\
728 -o, --output=FILE Write output to FILE.\n\
730 { "decrypt", decrypt
,
731 "decrypt [-aqv] [-f FORMAT] [-o OUTPUT] [FILE]", "\
734 -a, --armour Same as `-f pem'.\n\
735 -v, --verbose Produce more verbose messages.\n\
736 -q, --quiet Produce fewer messages.\n\
737 -f, --format=FORMAT Decode as FORMAT.\n\
738 -o, --output=FILE Write output to FILE.\n\
743 static int cmd_help(int argc
, char **argv
)
745 sc_help(cmdtab
, stdout
, argv
+ 1);
749 void version(FILE *fp
)
751 pquis(fp
, "$, Catacomb version " VERSION
"\n");
754 static void usage(FILE *fp
)
756 pquis(fp
, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
759 void help_global(FILE *fp
)
763 Encrypt and decrypt files.\n\
765 Global command-line options:\n\
767 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
768 -v, --version Show program version number.\n\
769 -u, --usage Show a terse usage message.\n\
771 -k, --keyring=FILE Read keys from FILE.\n",
777 * Arguments: @int argc@ = number of command line arguments
778 * @char *argv[]@ = vector of command line arguments
780 * Returns: Zero if successful, nonzero otherwise.
782 * Use: Encrypts or decrypts files.
785 int main(int argc
, char *argv
[])
791 /* --- Initialize the library --- */
795 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
796 rand_seed(RAND_GLOBAL
, 160);
798 /* --- Parse options --- */
801 static struct option opts
[] = {
802 { "help", 0, 0, 'h' },
803 { "version", 0, 0, 'v' },
804 { "usage", 0, 0, 'u' },
805 { "keyring", OPTF_ARGREQ
, 0, 'k' },
808 int i
= mdwopt(argc
, argv
, "+hvu k:", opts
, 0, 0, 0);
813 sc_help(cmdtab
, stdout
, argv
+ optind
);
835 if (f
& f_bogus
|| argc
< 1) {
840 /* --- Dispatch to the correct subcommand handler --- */
842 return (findcmd(cmdtab
, argv
[0])->cmd(argc
, argv
));
847 /*----- That's all, folks -------------------------------------------------*/