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. This hash is what is signed if
92 * the message is signed. The hash is expanded using an MGF (or similar) to
93 * make a symmetric encryption and MAC key.
95 * If the message is signed, there comes a signature chunk. The signature is
96 * on the secret hash. This means that the recipient can modify the message
97 * and still have a valid signature, so it's not useful for proving things to
98 * other people; but it also means that the recipient knows that the message
99 * is from someone who knows the hash, which limits the possiblities to (a)
100 * whoever encrypted the message (good!) and (b) whoever knows the
101 * recipient's private key.
103 * Then come message chunks. Each one begins with a MAC over an implicit
104 * sequence number and the ciphertext. The final chunk's ciphertext is
105 * empty; no other chunk is empty. Thus can the correct end-of-file be
109 /*----- Chunk I/O ---------------------------------------------------------*/
111 static void chunk_write(enc
*e
, buf
*b
)
117 if (e
->ops
->write(e
, l
, 2) ||
118 e
->ops
->write(e
, BBASE(b
), BLEN(b
)))
119 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
122 static void chunk_read(enc
*e
, dstr
*d
, buf
*b
)
129 if (e
->ops
->read(e
, l
, 2) != 2)
133 if (e
->ops
->read(e
, d
->buf
, n
) != n
)
136 buf_init(b
, d
->buf
, d
->len
);
140 if (!errno
) die(EXIT_FAILURE
, "unexpected end-of-file on input");
141 else die(EXIT_FAILURE
, "error reading input: %s", strerror(errno
));
144 /*----- Encryption --------------------------------------------------------*/
146 static int encrypt(int argc
, char *argv
[])
148 const char *of
= 0, *kn
= "ccrypt", *skn
= 0;
151 const char *ef
= "binary";
176 static const struct option opt
[] = {
177 { "key", OPTF_ARGREQ
, 0, 'k' },
178 { "sign-key", OPTF_ARGREQ
, 0, 's' },
179 { "armour", 0, 0, 'a' },
180 { "armor", 0, 0, 'a' },
181 { "format", OPTF_ARGREQ
, 0, 'f' },
182 { "output", OPTF_ARGREQ
, 0, 'o' },
185 i
= mdwopt(argc
, argv
, "k:s:af:o:", opt
, 0, 0, 0);
188 case 'k': kn
= optarg
; break;
189 case 's': skn
= optarg
; break;
190 case 'a': ef
= "pem"; break;
191 case 'f': ef
= optarg
; break;
192 case 'o': of
= optarg
; break;
193 default: f
|= f_bogus
; break;
196 if (argc
- optind
> 1 || (f
& f_bogus
))
197 die(EXIT_FAILURE
, "Usage: encrypt [-OPTIONS] [FILE]");
199 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
200 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
201 if ((k
= key_bytag(&kf
, kn
)) == 0)
202 die(EXIT_FAILURE
, "key `%s' not found", kn
);
203 if (skn
&& (sk
= key_bytag(&kf
, skn
)) == 0)
204 die(EXIT_FAILURE
, "key `%s' not found", skn
);
206 if ((eo
= getenc(ef
)) == 0)
207 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
211 else if (strcmp(argv
[optind
], "-") == 0) {
214 } else if ((fp
= fopen(argv
[optind
], "rb")) == 0) {
215 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
216 argv
[optind
], strerror(errno
));
220 if (!of
|| strcmp(of
, "-") == 0)
222 else if ((ofp
= fopen(of
, eo
->wmode
)) == 0) {
223 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
224 ofp
, strerror(errno
));
229 e
= initenc(eo
, ofp
, "CATCRYPT ENCRYPTED MESSAGE", 1);
230 km
= getkem(k
, "cckem", 0);
231 if ((err
= km
->ops
->check(km
)) != 0)
232 moan("key `%s' fails check: %s", d
.buf
, err
);
236 s
= getsig(sk
, "ccsig", 1);
237 if ((err
= s
->ops
->check(s
)) != 0)
238 moan("key `%s' fails check: %s", d
.buf
, err
);
241 /* --- Build the header chunk --- */
244 dstr_ensure(&d
, 256);
245 buf_init(&b
, d
.buf
, 256);
246 buf_putu32(&b
, k
->id
);
247 if (sk
) buf_putu32(&b
, sk
->id
);
251 /* --- Build the KEM chunk --- */
254 if (setupkem(km
, &d
, &cx
, &c
, &m
))
255 die(EXIT_FAILURE
, "failed to encapsulate key");
256 buf_init(&b
, d
.buf
, d
.len
);
260 /* --- Write the signature chunk --- */
263 GC_ENCRYPT(cx
, 0, bb
, 1024);
264 GH_HASH(s
->h
, bb
, 1024);
266 if ((en
= s
->ops
->doit(s
, &d
)) != 0)
267 die(EXIT_FAILURE
, "error creating signature: %s", key_strerror(en
));
268 buf_init(&b
, d
.buf
, d
.len
);
273 /* --- Now do the main crypto --- */
275 assert(GC_CLASS(c
)->blksz
<= sizeof(bb
));
276 dstr_ensure(&d
, sizeof(bb
) + GM_CLASS(m
)->hashsz
);
283 if (GC_CLASS(c
)->blksz
) {
284 GC_ENCRYPT(cx
, 0, bb
, GC_CLASS(c
)->blksz
);
287 n
= fread(bb
, 1, sizeof(bb
), fp
);
289 buf_init(&b
, d
.buf
, d
.sz
);
290 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
292 assert(tag
); assert(ct
);
293 GC_ENCRYPT(c
, bb
, ct
, n
);
300 /* --- Final terminator packet --- */
302 buf_init(&b
, d
.buf
, d
.sz
);
303 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
309 /* --- All done --- */
326 /*---- Decryption ---------------------------------------------------------*/
328 static int decrypt(int argc
, char *argv
[])
333 const char *ef
= "binary";
358 static const struct option opt
[] = {
359 { "armour", 0, 0, 'a' },
360 { "armor", 0, 0, 'a' },
361 { "verbose", 0, 0, 'v' },
362 { "quiet", 0, 0, 'q' },
363 { "format", OPTF_ARGREQ
, 0, 'f' },
364 { "output", OPTF_ARGREQ
, 0, 'o' },
367 i
= mdwopt(argc
, argv
, "af:o:qv", opt
, 0, 0, 0);
370 case 'a': ef
= "pem"; break;
371 case 'v': verb
++; break;
372 case 'q': if (verb
) verb
--; break;
373 case 'f': ef
= optarg
; break;
374 case 'o': of
= optarg
; break;
375 default: f
|= f_bogus
; break;
378 if (argc
- optind
> 1 || (f
& f_bogus
))
379 die(EXIT_FAILURE
, "Usage: decrypt [-OPTIONS] [FILE]");
381 if ((eo
= getenc(ef
)) == 0)
382 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
386 else if (strcmp(argv
[optind
], "-") == 0) {
389 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
390 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
391 argv
[optind
], strerror(errno
));
395 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
396 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
398 e
= initenc(eo
, fp
, "CATCRYPT ENCRYPTED MESSAGE", 0);
400 /* --- Read the header chunk --- */
402 chunk_read(e
, &d
, &b
);
403 if (buf_getu32(&b
, &id
)) {
404 if (verb
) printf("FAIL malformed header: missing keyid\n");
407 if ((k
= key_byid(&kf
, id
)) == 0) {
408 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
412 if (buf_getu32(&b
, &id
)) {
413 if (verb
) printf("FAIL malformed header: missing signature keyid\n");
416 if ((sk
= key_byid(&kf
, id
)) == 0) {
417 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
422 if (verb
) printf("FAIL malformed header: junk at end\n");
426 /* --- Find the key --- */
428 km
= getkem(k
, "cckem", 1);
430 /* --- Read the KEM chunk --- */
432 chunk_read(e
, &d
, &b
);
433 if (setupkem(km
, &d
, &cx
, &c
, &m
)) {
434 if (verb
) printf("FAIL failed to decapsulate key\n");
438 /* --- Verify the signature, if there is one --- */
441 s
= getsig(sk
, "ccsig", 0);
444 if (verb
&& (err
= s
->ops
->check(s
)) != 0)
445 printf("WARN verification key %s fails check: %s\n", d
.buf
, err
);
447 dstr_ensure(&d
, 1024);
448 GC_ENCRYPT(cx
, 0, d
.buf
, 1024);
449 GH_HASH(s
->h
, d
.buf
, 1024);
450 chunk_read(e
, &d
, &b
);
451 if (s
->ops
->doit(s
, &d
)) {
452 if (verb
) printf("FAIL signature verification failed\n");
458 printf("INFO good signature from %s\n", d
.buf
);
461 printf("INFO no signature packet\n");
463 /* --- Now decrypt the main body --- */
465 if (!of
|| strcmp(of
, "-") == 0) {
467 if (verb
) printf("DATA\n");
468 } else if ((ofp
= fopen(of
, "wb")) == 0) {
469 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
470 ofp
, strerror(errno
));
474 dstr_ensure(&d
, GC_CLASS(c
)->blksz
);
477 if (GC_CLASS(c
)->blksz
) {
478 GC_ENCRYPT(cx
, 0, d
.buf
, GC_CLASS(c
)->blksz
);
483 GH_HASH(h
, d
.buf
, 4);
485 chunk_read(e
, &d
, &b
);
486 if ((tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
)) == 0) {
487 if (verb
) printf("%sFAIL bad ciphertext chunk: no tag\n",
488 ofp
== stdout ?
"\n" : "");
491 GH_HASH(h
, BCUR(&b
), BLEFT(&b
));
492 if (memcmp(tag
, GH_DONE(h
, 0), GM_CLASS(m
)->hashsz
) != 0) {
494 printf("%sFAIL bad ciphertext chunk: authentication failure\n",
495 ofp
== stdout ?
"\n" : "");
500 GC_DECRYPT(c
, BCUR(&b
), BCUR(&b
), BLEFT(&b
));
501 if (fwrite(BCUR(&b
), 1, BLEFT(&b
), ofp
) != BLEFT(&b
)) {
502 if (verb
) printf("%sFAIL error writing output: %s\n",
503 ofp
== stdout ?
"\n" : "", strerror(errno
));
508 if (fflush(ofp
) || ferror(ofp
)) {
509 if (verb
) printf("%sFAIL error writing output: %s\n",
510 ofp
== stdout ?
"\n" : "", strerror(errno
));
515 if (verb
&& ofp
!= stdout
)
516 printf("OK decrypted successfully\n");
530 /*----- Test code ---------------------------------------------------------*/
532 static int encode(int argc
, char *argv
[])
537 const char *ef
= "binary";
538 const char *bd
= "MESSAGE";
549 static const struct option opt
[] = {
550 { "format", OPTF_ARGREQ
, 0, 'f' },
551 { "boundary", OPTF_ARGREQ
, 0, 'b' },
552 { "output", OPTF_ARGREQ
, 0, 'o' },
555 i
= mdwopt(argc
, argv
, "f:b:o:", opt
, 0, 0, 0);
558 case 'f': ef
= optarg
; break;
559 case 'b': bd
= optarg
; break;
560 case 'o': of
= optarg
; break;
561 default: f
|= f_bogus
; break;
564 if (argc
- optind
> 1 || (f
& f_bogus
))
565 die(EXIT_FAILURE
, "Usage: encode [-OPTIONS] [FILE]");
567 if ((eo
= getenc(ef
)) == 0)
568 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
572 else if (strcmp(argv
[optind
], "-") == 0) {
575 } else if ((fp
= fopen(argv
[optind
], "rb")) == 0) {
576 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
577 argv
[optind
], strerror(errno
));
581 if (!of
|| strcmp(of
, "-") == 0)
583 else if ((ofp
= fopen(of
, eo
->wmode
)) == 0) {
584 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
585 ofp
, strerror(errno
));
588 e
= initenc(eo
, ofp
, bd
, 1);
591 n
= fread(buf
, 1, sizeof(buf
), fp
);
592 if (e
->ops
->write(e
, buf
, n
))
593 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
594 } while (n
== sizeof(buf
));
602 static int decode(int argc
, char *argv
[])
607 const char *ef
= "binary";
618 static const struct option opt
[] = {
619 { "format", OPTF_ARGREQ
, 0, 'f' },
620 { "boundary", OPTF_ARGREQ
, 0, 'b' },
621 { "output", OPTF_ARGREQ
, 0, 'o' },
624 i
= mdwopt(argc
, argv
, "f:b:o:", opt
, 0, 0, 0);
627 case 'f': ef
= optarg
; break;
628 case 'b': bd
= optarg
; break;
629 case 'o': of
= optarg
; break;
630 default: f
|= f_bogus
; break;
633 if (argc
- optind
> 1 || (f
& f_bogus
))
634 die(EXIT_FAILURE
, "Usage: decode [-OPTIONS] [FILE]");
636 if ((eo
= getenc(ef
)) == 0)
637 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
641 else if (strcmp(argv
[optind
], "-") == 0) {
644 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
645 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
646 argv
[optind
], strerror(errno
));
650 if (!of
|| strcmp(of
, "-") == 0)
652 else if ((ofp
= fopen(of
, "wb")) == 0) {
653 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
654 ofp
, strerror(errno
));
657 e
= initenc(eo
, fp
, bd
, 0);
660 if ((i
= e
->ops
->read(e
, buf
, sizeof(buf
))) < 0)
661 die(EXIT_FAILURE
, "error reading input: %s", strerror(errno
));
662 if (fwrite(buf
, 1, i
, ofp
) < i
)
663 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
664 } while (i
== sizeof(buf
));
672 /*----- Main code ---------------------------------------------------------*/
676 listtab[i].name, listtab[i].name) \
677 LI("Key-encapsulation mechanisms", kem, \
678 kemtab[i].name, kemtab[i].name) \
679 LI("Signature schemes", sig, \
680 sigtab[i].name, sigtab[i].name) \
681 LI("Encodings", enc, \
682 enctab[i].name, enctab[i].name) \
683 LI("Symmetric encryption algorithms", cipher, \
684 gciphertab[i], gciphertab[i]->name) \
685 LI("Hash functions", hash, \
686 ghashtab[i], ghashtab[i]->name) \
687 LI("Message authentication codes", mac, \
688 gmactab[i], gmactab[i]->name)
690 MAKELISTTAB(listtab
, LISTS
)
692 int cmd_show(int argc
, char *argv
[])
694 return (displaylists(listtab
, argv
+ 1));
697 static int cmd_help(int, char **);
699 static cmd cmdtab
[] = {
700 { "help", cmd_help
, "help [COMMAND...]" },
701 { "show", cmd_show
, "show [ITEM...]" },
703 "encode [-f FORMAT] [-b LABEL] [-o OUTPUT] [FILE]",
707 -f, --format=FORMAT Encode to FORMAT.\n\
708 -b, --boundary=LABEL PEM boundary is LABEL.\n\
709 -o, --output=FILE Write output to FILE.\n\
712 "decode [-f FORMAT] [-b LABEL] [-o OUTPUT] [FILE]",
716 -f, --format=FORMAT Decode from FORMAT.\n\
717 -b, --boundary=LABEL PEM boundary is LABEL.\n\
718 -o, --output=FILE Write output to FILE.\n\
720 { "encrypt", encrypt
,
721 "encrypt [-a] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
722 [-o OUTPUT] [FILE]", "\
725 -a, --armour Same as `-f pem'.\n\
726 -f, --format=FORMAT Encode as FORMAT.\n\
727 -k, --key=TAG Use public encryption key named by TAG.\n\
728 -s, --sign-key=TAG Use private signature key named by TAG.\n\
729 -o, --output=FILE Write output to FILE.\n\
731 { "decrypt", decrypt
,
732 "decrypt [-aqv] [-f FORMAT] [-o OUTPUT] [FILE]", "\
735 -a, --armour Same as `-f pem'.\n\
736 -v, --verbose Produce more verbose messages.\n\
737 -q, --quiet Produce fewer messages.\n\
738 -f, --format=FORMAT Decode as FORMAT.\n\
739 -o, --output=FILE Write output to FILE.\n\
744 static int cmd_help(int argc
, char **argv
)
746 sc_help(cmdtab
, stdout
, argv
+ 1);
750 void version(FILE *fp
)
752 pquis(fp
, "$, Catacomb version " VERSION
"\n");
755 static void usage(FILE *fp
)
757 pquis(fp
, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
760 void help_global(FILE *fp
)
764 Encrypt and decrypt files.\n\
766 Global command-line options:\n\
768 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
769 -v, --version Show program version number.\n\
770 -u, --usage Show a terse usage message.\n\
772 -k, --keyring=FILE Read keys from FILE.\n",
778 * Arguments: @int argc@ = number of command line arguments
779 * @char *argv[]@ = vector of command line arguments
781 * Returns: Zero if successful, nonzero otherwise.
783 * Use: Encrypts or decrypts files.
786 int main(int argc
, char *argv
[])
792 /* --- Initialize the library --- */
796 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
797 rand_seed(RAND_GLOBAL
, 160);
799 /* --- Parse options --- */
802 static struct option opts
[] = {
803 { "help", 0, 0, 'h' },
804 { "version", 0, 0, 'v' },
805 { "usage", 0, 0, 'u' },
806 { "keyring", OPTF_ARGREQ
, 0, 'k' },
809 int i
= mdwopt(argc
, argv
, "+hvu k:", opts
, 0, 0, 0);
814 sc_help(cmdtab
, stdout
, argv
+ optind
);
836 if (f
& f_bogus
|| argc
< 1) {
841 /* --- Dispatch to the correct subcommand handler --- */
843 return (findcmd(cmdtab
, argv
[0])->cmd(argc
, argv
));
848 /*----- That's all, folks -------------------------------------------------*/