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 ------------------------------------------------------*/
32 #define _FILE_OFFSET_BITS 64
41 #include <mLib/base64.h>
42 #include <mLib/dstr.h>
43 #include <mLib/mdwopt.h>
44 #include <mLib/quis.h>
45 #include <mLib/report.h>
58 /*----- Static variables --------------------------------------------------*/
60 static const char *keyring = "keyring";
62 /*----- Data format -------------------------------------------------------*/
66 * The encrypted message is divided into chunks, each preceded by a two-octet
67 * length. The chunks don't need to be large -- the idea is that we can
68 * stream the chunks in and out.
70 * The first chunk is a header. It contains the decryption key-id, and maybe
71 * the verification key-id if the message is signed.
73 * Next comes the key-encapsulation chunk. This is decrypted in some
74 * KEM-specific way to yield a secret hash. The hash is expanded using an
75 * MGF (or similar) to make a symmetric encryption and MAC key.
77 * If the message is signed, there comes a signature chunk. The signature is
78 * on the header and key-encapsulation chunks, and further output of the MGF.
79 * This means that the recipient can modify the message and still have a
80 * valid signature, so it's not useful for proving things to other people;
81 * but it also means that the recipient knows that the message is from
82 * someone who knows the hash, which limits the possiblities to (a) whoever
83 * encrypted the message (good!) and (b) whoever knows the recipient's
86 * Then come message chunks. Each one begins with a MAC over an implicit
87 * sequence number and the ciphertext. The final chunk's ciphertext is
88 * empty; no other chunk is empty. Thus can the correct end-of-file be
92 /*----- Chunk I/O ---------------------------------------------------------*/
94 static void chunk_write(enc *e, buf *b)
100 if (e->ops->write(e, l, 2) ||
101 e->ops->write(e, BBASE(b), BLEN(b)))
102 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
105 static void chunk_read(enc *e, dstr *d, buf *b)
112 if (e->ops->read(e, l, 2) != 2)
116 if (e->ops->read(e, d->buf, n) != n)
119 buf_init(b, d->buf, d->len);
123 if (!errno) die(EXIT_FAILURE, "unexpected end-of-file on input");
124 else die(EXIT_FAILURE, "error reading input: %s", strerror(errno));
127 /*----- Encryption --------------------------------------------------------*/
129 static int encrypt(int argc, char *argv[])
131 const char *fn, *of = 0, *kn = "ccrypt", *skn = 0;
134 const char *ef = "binary";
159 #define f_progress 4u
162 static const struct option opt[] = {
163 { "key", OPTF_ARGREQ, 0, 'k' },
164 { "sign-key", OPTF_ARGREQ, 0, 's' },
165 { "armour", 0, 0, 'a' },
166 { "armor", 0, 0, 'a' },
167 { "format", OPTF_ARGREQ, 0, 'f' },
168 { "output", OPTF_ARGREQ, 0, 'o' },
169 { "progress", 0, 0, 'p' },
170 { "nocheck", 0, 0, 'C' },
173 i = mdwopt(argc, argv, "k:s:af:o:pC", opt, 0, 0, 0);
176 case 'k': kn = optarg; break;
177 case 's': skn = optarg; break;
178 case 'a': ef = "pem"; break;
179 case 'f': ef = optarg; break;
180 case 'o': of = optarg; break;
181 case 'p': f |= f_progress; break;
182 case 'C': f |= f_nocheck; break;
183 default: f |= f_bogus; break;
186 if (argc - optind > 1 || (f & f_bogus))
187 die(EXIT_FAILURE, "Usage: encrypt [-OPTIONS] [FILE]");
189 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
190 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
191 if ((k = key_bytag(&kf, kn)) == 0)
192 die(EXIT_FAILURE, "key `%s' not found", kn);
193 if (skn && (sk = key_bytag(&kf, skn)) == 0)
194 die(EXIT_FAILURE, "key `%s' not found", skn);
196 if ((eo = getenc(ef)) == 0)
197 die(EXIT_FAILURE, "encoding `%s' not found", ef);
199 fn = optind < argc ? argv[optind++] : "-";
200 if (strcmp(fn, "-") == 0)
202 else if ((fp = fopen(fn, "rb")) == 0) {
203 die(EXIT_FAILURE, "couldn't open file `%s': %s",
204 fn, strerror(errno));
207 if (!of || strcmp(of, "-") == 0)
209 else if ((ofp = fopen(of, eo->wmode)) == 0) {
210 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
211 ofp, strerror(errno));
216 e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE");
217 km = getkem(k, "cckem", 0);
218 if (!(f & f_nocheck) && (err = km->ops->check(km)) != 0)
219 moan("key %s fails check: %s", d.buf, err);
223 s = getsig(sk, "ccsig", 1);
224 if ((err = s->ops->check(s)) != 0)
225 moan("key %s fails check: %s", d.buf, err);
228 /* --- Build the header chunk --- */
231 dstr_ensure(&d, 256);
232 buf_init(&b, d.buf, 256);
233 buf_putu32(&b, k->id);
234 if (sk) buf_putu32(&b, sk->id);
236 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
239 /* --- Build the KEM chunk --- */
242 if (setupkem(km, &d, &cx, &c, &m))
243 die(EXIT_FAILURE, "failed to encapsulate key");
244 buf_init(&b, d.buf, d.len);
246 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
249 /* --- Write the signature chunk --- */
252 GC_ENCRYPT(cx, 0, bb, 1024);
253 GH_HASH(s->h, bb, 1024);
255 if ((en = s->ops->doit(s, &d)) != 0)
256 die(EXIT_FAILURE, "error creating signature: %s", key_strerror(en));
257 buf_init(&b, d.buf, d.len);
262 /* --- Now do the main crypto --- */
264 if (f & f_progress) {
265 if (fprogress_init(&ff, fn, fp)) {
266 die(EXIT_FAILURE, "failed to initialize progress display: %s",
271 assert(GC_CLASS(c)->blksz <= sizeof(bb));
272 dstr_ensure(&d, sizeof(bb) + GM_CLASS(m)->hashsz);
274 chsz = MASK16 - GM_CLASS(m)->hashsz;
279 if (GC_CLASS(c)->blksz) {
280 GC_ENCRYPT(cx, 0, bb, GC_CLASS(c)->blksz);
283 n = fread(bb, 1, chsz, fp);
285 if (f & f_progress) fprogress_update(&ff, n);
286 buf_init(&b, d.buf, d.sz);
287 tag = buf_get(&b, GM_CLASS(m)->hashsz);
289 assert(tag); assert(ct);
290 GC_ENCRYPT(c, bb, ct, n);
297 /* --- Final terminator packet --- */
299 buf_init(&b, d.buf, d.sz);
300 tag = buf_get(&b, GM_CLASS(m)->hashsz);
306 /* --- All done --- */
308 if (f & f_progress) fprogress_done(&ff);
316 if (fp != stdin) fclose(fp);
327 /*---- Decryption ---------------------------------------------------------*/
329 static int decrypt(int argc, char *argv[])
331 const char *fn, *of = 0;
332 FILE *ofp = 0, *rfp = 0;
334 const char *ef = "binary";
361 #define f_progress 8u
364 static const struct option opt[] = {
365 { "armour", 0, 0, 'a' },
366 { "armor", 0, 0, 'a' },
367 { "buffer", 0, 0, 'b' },
368 { "verbose", 0, 0, 'v' },
369 { "quiet", 0, 0, 'q' },
370 { "nocheck", 0, 0, 'C' },
371 { "format", OPTF_ARGREQ, 0, 'f' },
372 { "output", OPTF_ARGREQ, 0, 'o' },
373 { "progress", 0, 0, 'p' },
376 i = mdwopt(argc, argv, "abf:o:pqvC", opt, 0, 0, 0);
379 case 'a': ef = "pem"; break;
380 case 'b': f |= f_buffer; break;
381 case 'v': verb++; break;
382 case 'q': if (verb) verb--; break;
383 case 'C': f |= f_nocheck; break;
384 case 'f': ef = optarg; break;
385 case 'o': of = optarg; break;
386 case 'p': f |= f_progress; break;
387 default: f |= f_bogus; break;
390 if (argc - optind > 1 || (f & f_bogus))
391 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
393 if ((eo = getenc(ef)) == 0)
394 die(EXIT_FAILURE, "encoding `%s' not found", ef);
396 fn = optind < argc ? argv[optind++] : "-";
397 if (strcmp(fn, "-") == 0)
399 else if ((fp = fopen(fn, eo->rmode)) == 0) {
400 die(EXIT_FAILURE, "couldn't open file `%s': %s",
401 fn, strerror(errno));
404 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
405 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
407 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
409 if (f & f_progress) {
410 if (fprogress_init(&ff, fn, fp)) {
411 die(EXIT_FAILURE, "failed to initialize progress display: %s",
416 /* --- Read the header chunk --- */
418 chunk_read(e, &d, &b);
420 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
421 if (buf_getu32(&b, &id)) {
422 if (f & f_progress) fprogress_done(&ff);
423 if (verb) printf("FAIL malformed header: missing keyid\n");
426 if ((k = key_byid(&kf, id)) == 0) {
427 if (f & f_progress) fprogress_done(&ff);
428 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
432 if (buf_getu32(&b, &id)) {
433 if (f & f_progress) fprogress_done(&ff);
434 if (verb) printf("FAIL malformed header: missing signature keyid\n");
437 if ((sk = key_byid(&kf, id)) == 0) {
438 if (f & f_progress) fprogress_done(&ff);
439 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
444 if (f & f_progress) fprogress_done(&ff);
445 if (verb) printf("FAIL malformed header: junk at end\n");
449 s = getsig(sk, "ccsig", 0);
450 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0) {
453 printf("WARN verification key %s fails check: %s\n", d.buf, err);
455 GH_HASHBUF16(s->h, BBASE(&b), BSZ(&b));
458 /* --- Find the key --- */
460 km = getkem(k, "cckem", 1);
462 /* --- Read the KEM chunk --- */
464 chunk_read(e, &d, &b);
466 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
467 if (setupkem(km, &d, &cx, &c, &m)) {
468 if (f & f_progress) fprogress_done(&ff);
469 if (verb) printf("FAIL failed to decapsulate key\n");
472 if (s) GH_HASHBUF16(s->h, d.buf, d.len);
474 /* --- Verify the signature, if there is one --- */
478 dstr_ensure(&d, 1024);
479 GC_ENCRYPT(cx, 0, d.buf, 1024);
480 GH_HASH(s->h, d.buf, 1024);
481 chunk_read(e, &d, &b);
483 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
484 if (s->ops->doit(s, &d)) {
485 if (f & f_progress) fprogress_done(&ff);
486 if (verb) printf("FAIL signature verification failed\n");
492 if (f & f_progress) fprogress_clear(&ff);
493 printf("INFO good-signature %s\n", d.buf);
497 if (f & f_progress) fprogress_clear(&ff);
498 printf("INFO no-signature\n");
501 /* --- Now decrypt the main body --- */
503 if (!of || strcmp(of, "-") == 0) {
507 if (!(f & f_buffer)) {
508 if ((ofp = fopen(of, "wb")) == 0) {
509 if (f & f_progress) fprogress_done(&ff);
510 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
511 ofp, strerror(errno));
514 } else if ((rfp = tmpfile()) == 0) {
515 if (f & f_progress) fprogress_done(&ff);
516 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
520 dstr_ensure(&d, GC_CLASS(c)->blksz);
523 if (GC_CLASS(c)->blksz) {
524 GC_ENCRYPT(cx, 0, d.buf, GC_CLASS(c)->blksz);
530 chunk_read(e, &d, &b);
532 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
533 if ((tag = buf_get(&b, GM_CLASS(m)->hashsz)) == 0) {
534 if (f & f_progress) fprogress_done(&ff);
535 if (verb) printf("FAIL bad ciphertext chunk: no tag\n");
538 GH_HASH(h, BCUR(&b), BLEFT(&b));
539 if (memcmp(tag, GH_DONE(h, 0), GM_CLASS(m)->hashsz) != 0) {
540 if (f & f_progress) fprogress_done(&ff);
542 printf("FAIL bad ciphertext chunk: authentication failure\n");
548 GC_DECRYPT(c, BCUR(&b), BCUR(&b), BLEFT(&b));
549 if (fwrite(BCUR(&b), 1, BLEFT(&b), rfp) != BLEFT(&b)) {
550 if (f & f_progress) fprogress_done(&ff);
551 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
556 if (f & f_progress) fprogress_done(&ff);
557 if (fflush(rfp) || ferror(rfp)) {
558 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
562 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
563 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
564 of, strerror(errno));
567 if (f & f_progress) fprogress_init(&ff, "copying buffer", rfp);
569 dstr_ensure(&d, 65536);
570 if (verb && ofp == stdout) printf("DATA\n");
572 n = fread(d.buf, 1, d.sz, rfp);
574 if (f & f_progress) fprogress_update(&ff, n);
575 if (fwrite(d.buf, 1, n, ofp) < n) {
576 if (f & f_progress) fprogress_done(&ff);
577 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
580 if (f & f_progress) fprogress_done(&ff);
581 if (ferror(rfp) || fclose(rfp))
582 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
586 if (verb && ofp != stdout)
587 printf("OK decrypted successfully\n");
588 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
589 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
595 if (fp != stdin) fclose(fp);
606 /*----- Main code ---------------------------------------------------------*/
610 listtab[i].name, listtab[i].name) \
611 LI("Key-encapsulation mechanisms", kem, \
612 kemtab[i].name, kemtab[i].name) \
613 LI("Signature schemes", sig, \
614 sigtab[i].name, sigtab[i].name) \
615 LI("Encodings", enc, \
616 enctab[i].name, enctab[i].name) \
617 LI("Symmetric encryption algorithms", cipher, \
618 gciphertab[i], gciphertab[i]->name) \
619 LI("Hash functions", hash, \
620 ghashtab[i], ghashtab[i]->name) \
621 LI("Message authentication codes", mac, \
622 gmactab[i], gmactab[i]->name)
624 MAKELISTTAB(listtab, LISTS)
626 int cmd_show(int argc, char *argv[])
628 return (displaylists(listtab, argv + 1));
631 static int cmd_help(int, char **);
633 static cmd cmdtab[] = {
634 { "help", cmd_help, "help [COMMAND...]" },
635 { "show", cmd_show, "show [ITEM...]" },
638 { "encrypt", encrypt,
639 "encrypt [-apC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
640 [-o OUTPUT] [FILE]", "\
643 -a, --armour Same as `-f pem'.\n\
644 -f, --format=FORMAT Encode as FORMAT.\n\
645 -k, --key=TAG Use public encryption key named by TAG.\n\
646 -s, --sign-key=TAG Use private signature key named by TAG.\n\
647 -o, --output=FILE Write output to FILE.\n\
648 -p, --progress Show progress on large files.\n\
649 -C, --nocheck Don't check the public key.\n\
651 { "decrypt", decrypt,
652 "decrypt [-abpqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
655 -a, --armour Same as `-f pem'.\n\
656 -b, --buffer Buffer output until we're sure we have it all.\n\
657 -f, --format=FORMAT Decode as FORMAT.\n\
658 -o, --output=FILE Write output to FILE.\n\
659 -p, --progress Show progress on large files.\n\
660 -q, --quiet Produce fewer messages.\n\
661 -v, --verbose Produce more verbose messages.\n\
662 -C, --nocheck Don't check the private key.\n\
667 static int cmd_help(int argc, char **argv)
669 sc_help(cmdtab, stdout, argv + 1);
673 void version(FILE *fp)
675 pquis(fp, "$, Catacomb version " VERSION "\n");
678 static void usage(FILE *fp)
680 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
683 void help_global(FILE *fp)
687 Encrypt and decrypt files.\n\
689 Global command-line options:\n\
691 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
692 -v, --version Show program version number.\n\
693 -u, --usage Show a terse usage message.\n\
695 -k, --keyring=FILE Read keys from FILE.\n",
701 * Arguments: @int argc@ = number of command line arguments
702 * @char *argv[]@ = vector of command line arguments
704 * Returns: Zero if successful, nonzero otherwise.
706 * Use: Encrypts or decrypts files.
709 int main(int argc, char *argv[])
715 /* --- Initialize the library --- */
719 rand_noisesrc(RAND_GLOBAL, &noise_source);
720 rand_seed(RAND_GLOBAL, 160);
722 /* --- Parse options --- */
725 static struct option opts[] = {
726 { "help", 0, 0, 'h' },
727 { "version", 0, 0, 'v' },
728 { "usage", 0, 0, 'u' },
729 { "keyring", OPTF_ARGREQ, 0, 'k' },
732 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
737 sc_help(cmdtab, stdout, argv + optind);
759 if (f & f_bogus || argc < 1) {
764 /* --- Dispatch to the correct subcommand handler --- */
766 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
771 /*----- That's all, folks -------------------------------------------------*/