3 * Command-line encryption tool
5 * (c) 2004 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
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>
57 /*----- Static variables --------------------------------------------------*/
59 static const char *keyring = "keyring";
61 /*----- Data format -------------------------------------------------------*/
65 * The encrypted message is divided into chunks, each preceded by a two-octet
66 * length. The chunks don't need to be large -- the idea is that we can
67 * stream the chunks in and out.
69 * The first chunk is a header. It contains the decryption key-id, and maybe
70 * the verification key-id if the message is signed.
72 * Next comes the key-encapsulation chunk. This is decrypted in some
73 * KEM-specific way to yield a secret hash. The hash is expanded using an
74 * MGF (or similar) to make a symmetric encryption and MAC key.
76 * If the message is signed, there comes a signature chunk. The signature is
77 * on the header and key-encapsulation chunks, and further output of the MGF.
78 * This means that the recipient can modify the message and still have a
79 * valid signature, so it's not useful for proving things to other people;
80 * but it also means that the recipient knows that the message is from
81 * someone who knows the hash, which limits the possiblities to (a) whoever
82 * encrypted the message (good!) and (b) whoever knows the recipient's
85 * Then come message chunks. Each one begins with a MAC over an implicit
86 * sequence number and the ciphertext. The final chunk's ciphertext is
87 * empty; no other chunk is empty. Thus can the correct end-of-file be
91 /*----- Chunk I/O ---------------------------------------------------------*/
93 static void chunk_write(enc *e, buf *b)
99 if (e->ops->write(e, l, 2) ||
100 e->ops->write(e, BBASE(b), BLEN(b)))
101 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
104 static void chunk_read(enc *e, dstr *d, buf *b)
111 if (e->ops->read(e, l, 2) != 2)
115 if (e->ops->read(e, d->buf, n) != n)
118 buf_init(b, d->buf, d->len);
122 if (!errno) die(EXIT_FAILURE, "unexpected end-of-file on input");
123 else die(EXIT_FAILURE, "error reading input: %s", strerror(errno));
126 /*----- Encryption --------------------------------------------------------*/
128 static int encrypt(int argc, char *argv[])
130 const char *fn, *of = 0, *kn = "ccrypt", *skn = 0;
133 const char *ef = "binary";
158 #define f_progress 4u
161 static const struct option opt[] = {
162 { "key", OPTF_ARGREQ, 0, 'k' },
163 { "sign-key", OPTF_ARGREQ, 0, 's' },
164 { "armour", 0, 0, 'a' },
165 { "armor", 0, 0, 'a' },
166 { "format", OPTF_ARGREQ, 0, 'f' },
167 { "output", OPTF_ARGREQ, 0, 'o' },
168 { "progress", 0, 0, 'p' },
169 { "nocheck", 0, 0, 'C' },
172 i = mdwopt(argc, argv, "k:s:af:o:pC", opt, 0, 0, 0);
175 case 'k': kn = optarg; break;
176 case 's': skn = optarg; break;
177 case 'a': ef = "pem"; break;
178 case 'f': ef = optarg; break;
179 case 'o': of = optarg; break;
180 case 'p': f |= f_progress; break;
181 case 'C': f |= f_nocheck; break;
182 default: f |= f_bogus; break;
185 if (argc - optind > 1 || (f & f_bogus))
186 die(EXIT_FAILURE, "Usage: encrypt [-OPTIONS] [FILE]");
188 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
189 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
190 if ((k = key_bytag(&kf, kn)) == 0)
191 die(EXIT_FAILURE, "key `%s' not found", kn);
192 if (skn && (sk = key_bytag(&kf, skn)) == 0)
193 die(EXIT_FAILURE, "key `%s' not found", skn);
195 if ((eo = getenc(ef)) == 0)
196 die(EXIT_FAILURE, "encoding `%s' not found", ef);
198 fn = optind < argc ? argv[optind++] : "-";
199 if (strcmp(fn, "-") == 0)
201 else if ((fp = fopen(fn, "rb")) == 0) {
202 die(EXIT_FAILURE, "couldn't open file `%s': %s",
203 fn, strerror(errno));
206 if (!of || strcmp(of, "-") == 0)
208 else if ((ofp = fopen(of, eo->wmode)) == 0) {
209 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
210 of, strerror(errno));
215 e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE");
216 km = getkem(k, "cckem", 0);
217 if (!(f & f_nocheck) && (err = km->ops->check(km)) != 0)
218 moan("key %s fails check: %s", d.buf, err);
222 s = getsig(sk, "ccsig", 1);
223 if ((err = s->ops->check(s)) != 0)
224 moan("key %s fails check: %s", d.buf, err);
227 /* --- Build the header chunk --- */
230 dstr_ensure(&d, 256);
231 buf_init(&b, d.buf, 256);
232 buf_putu32(&b, k->id);
233 if (sk) buf_putu32(&b, sk->id);
235 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
238 /* --- Build the KEM chunk --- */
241 if (setupkem(km, &d, &cx, &c, &m))
242 die(EXIT_FAILURE, "failed to encapsulate key");
243 buf_init(&b, d.buf, d.len);
245 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
248 /* --- Write the signature chunk --- */
251 GC_ENCRYPT(cx, 0, bb, 1024);
252 GH_HASH(s->h, bb, 1024);
254 if ((en = s->ops->doit(s, &d)) != 0)
255 die(EXIT_FAILURE, "error creating signature: %s", key_strerror(en));
256 buf_init(&b, d.buf, d.len);
261 /* --- Now do the main crypto --- */
263 if (f & f_progress) {
264 if (fprogress_init(&ff, fn, fp)) {
265 die(EXIT_FAILURE, "failed to initialize progress display: %s",
270 assert(GC_CLASS(c)->blksz <= sizeof(bb));
271 dstr_ensure(&d, sizeof(bb) + GM_CLASS(m)->hashsz);
273 chsz = MASK16 - GM_CLASS(m)->hashsz;
278 if (GC_CLASS(c)->blksz) {
279 GC_ENCRYPT(cx, 0, bb, GC_CLASS(c)->blksz);
282 n = fread(bb, 1, chsz, fp);
284 if (f & f_progress) fprogress_update(&ff, n);
285 buf_init(&b, d.buf, d.sz);
286 tag = buf_get(&b, GM_CLASS(m)->hashsz);
288 assert(tag); assert(ct);
289 GC_ENCRYPT(c, bb, ct, n);
296 /* --- Final terminator packet --- */
298 buf_init(&b, d.buf, d.sz);
299 tag = buf_get(&b, GM_CLASS(m)->hashsz);
305 /* --- All done --- */
307 if (f & f_progress) fprogress_done(&ff);
315 if (fp != stdin) fclose(fp);
326 /*---- Decryption ---------------------------------------------------------*/
328 static int decrypt(int argc, char *argv[])
330 const char *fn, *of = 0;
331 FILE *ofp = 0, *rfp = 0;
333 const char *ef = "binary";
360 #define f_progress 8u
363 static const struct option opt[] = {
364 { "armour", 0, 0, 'a' },
365 { "armor", 0, 0, 'a' },
366 { "buffer", 0, 0, 'b' },
367 { "verbose", 0, 0, 'v' },
368 { "quiet", 0, 0, 'q' },
369 { "nocheck", 0, 0, 'C' },
370 { "format", OPTF_ARGREQ, 0, 'f' },
371 { "output", OPTF_ARGREQ, 0, 'o' },
372 { "progress", 0, 0, 'p' },
375 i = mdwopt(argc, argv, "abf:o:pqvC", opt, 0, 0, 0);
378 case 'a': ef = "pem"; break;
379 case 'b': f |= f_buffer; break;
380 case 'v': verb++; break;
381 case 'q': if (verb) verb--; break;
382 case 'C': f |= f_nocheck; break;
383 case 'f': ef = optarg; break;
384 case 'o': of = optarg; break;
385 case 'p': f |= f_progress; break;
386 default: f |= f_bogus; break;
389 if (argc - optind > 1 || (f & f_bogus))
390 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
392 if ((eo = getenc(ef)) == 0)
393 die(EXIT_FAILURE, "encoding `%s' not found", ef);
395 fn = optind < argc ? argv[optind++] : "-";
396 if (strcmp(fn, "-") == 0)
398 else if ((fp = fopen(fn, eo->rmode)) == 0) {
399 die(EXIT_FAILURE, "couldn't open file `%s': %s",
400 fn, strerror(errno));
403 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
404 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
406 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
408 if (f & f_progress) {
409 if (fprogress_init(&ff, fn, fp)) {
410 die(EXIT_FAILURE, "failed to initialize progress display: %s",
415 /* --- Read the header chunk --- */
417 chunk_read(e, &d, &b);
419 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
420 if (buf_getu32(&b, &id)) {
421 if (f & f_progress) fprogress_done(&ff);
422 if (verb) printf("FAIL malformed header: missing keyid\n");
425 if ((k = key_byid(&kf, id)) == 0) {
426 if (f & f_progress) fprogress_done(&ff);
427 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
431 if (buf_getu32(&b, &id)) {
432 if (f & f_progress) fprogress_done(&ff);
433 if (verb) printf("FAIL malformed header: missing signature keyid\n");
436 if ((sk = key_byid(&kf, id)) == 0) {
437 if (f & f_progress) fprogress_done(&ff);
438 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
443 if (f & f_progress) fprogress_done(&ff);
444 if (verb) printf("FAIL malformed header: junk at end\n");
448 s = getsig(sk, "ccsig", 0);
449 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0) {
452 printf("WARN verification key %s fails check: %s\n", d.buf, err);
454 GH_HASHBUF16(s->h, BBASE(&b), BSZ(&b));
457 /* --- Find the key --- */
459 km = getkem(k, "cckem", 1);
461 /* --- Read the KEM chunk --- */
463 chunk_read(e, &d, &b);
465 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
466 if (setupkem(km, &d, &cx, &c, &m)) {
467 if (f & f_progress) fprogress_done(&ff);
468 if (verb) printf("FAIL failed to decapsulate key\n");
471 if (s) GH_HASHBUF16(s->h, d.buf, d.len);
473 /* --- Verify the signature, if there is one --- */
477 dstr_ensure(&d, 1024);
478 GC_ENCRYPT(cx, 0, d.buf, 1024);
479 GH_HASH(s->h, d.buf, 1024);
480 chunk_read(e, &d, &b);
482 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
483 if (s->ops->doit(s, &d)) {
484 if (f & f_progress) fprogress_done(&ff);
485 if (verb) printf("FAIL signature verification failed\n");
491 if (f & f_progress) fprogress_clear(&ff);
492 printf("INFO good-signature %s\n", d.buf);
496 if (f & f_progress) fprogress_clear(&ff);
497 printf("INFO no-signature\n");
500 /* --- Now decrypt the main body --- */
502 if (!of || strcmp(of, "-") == 0) {
506 if (!(f & f_buffer)) {
507 if ((ofp = fopen(of, "wb")) == 0) {
508 if (f & f_progress) fprogress_done(&ff);
509 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
510 of, strerror(errno));
513 } else if ((rfp = tmpfile()) == 0) {
514 if (f & f_progress) fprogress_done(&ff);
515 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
519 dstr_ensure(&d, GC_CLASS(c)->blksz);
522 if (GC_CLASS(c)->blksz) {
523 GC_ENCRYPT(cx, 0, d.buf, GC_CLASS(c)->blksz);
529 chunk_read(e, &d, &b);
531 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
532 if ((tag = buf_get(&b, GM_CLASS(m)->hashsz)) == 0) {
533 if (f & f_progress) fprogress_done(&ff);
534 if (verb) printf("FAIL bad ciphertext chunk: no tag\n");
537 GH_HASH(h, BCUR(&b), BLEFT(&b));
538 if (!ct_memeq(tag, GH_DONE(h, 0), GM_CLASS(m)->hashsz)) {
539 if (f & f_progress) fprogress_done(&ff);
541 printf("FAIL bad ciphertext chunk: authentication failure\n");
547 GC_DECRYPT(c, BCUR(&b), BCUR(&b), BLEFT(&b));
548 if (fwrite(BCUR(&b), 1, BLEFT(&b), rfp) != BLEFT(&b)) {
549 if (f & f_progress) fprogress_done(&ff);
550 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
555 if (f & f_progress) fprogress_done(&ff);
556 if (fflush(rfp) || ferror(rfp)) {
557 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
561 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
562 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
563 of, strerror(errno));
566 if (f & f_progress) fprogress_init(&ff, "copying buffer", rfp);
568 dstr_ensure(&d, 65536);
569 if (verb && ofp == stdout) printf("DATA\n");
571 n = fread(d.buf, 1, d.sz, rfp);
573 if (f & f_progress) fprogress_update(&ff, n);
574 if (fwrite(d.buf, 1, n, ofp) < n) {
575 if (f & f_progress) fprogress_done(&ff);
576 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
579 if (f & f_progress) fprogress_done(&ff);
580 if (ferror(rfp) || fclose(rfp))
581 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
585 if (verb && ofp != stdout)
586 printf("OK decrypted successfully\n");
587 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
588 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
594 if (fp != stdin) fclose(fp);
605 /*----- Main code ---------------------------------------------------------*/
609 listtab[i].name, listtab[i].name) \
610 LI("Key-encapsulation mechanisms", kem, \
611 kemtab[i].name, kemtab[i].name) \
612 LI("Signature schemes", sig, \
613 sigtab[i].name, sigtab[i].name) \
614 LI("Encodings", enc, \
615 enctab[i].name, enctab[i].name) \
616 LI("Symmetric encryption algorithms", cipher, \
617 gciphertab[i], gciphertab[i]->name) \
618 LI("Hash functions", hash, \
619 ghashtab[i], ghashtab[i]->name) \
620 LI("Message authentication codes", mac, \
621 gmactab[i], gmactab[i]->name)
623 MAKELISTTAB(listtab, LISTS)
625 int cmd_show(int argc, char *argv[])
627 return (displaylists(listtab, argv + 1));
630 static int cmd_help(int, char **);
632 static cmd cmdtab[] = {
633 { "help", cmd_help, "help [COMMAND...]" },
634 { "show", cmd_show, "show [ITEM...]" },
637 { "encrypt", encrypt,
638 "encrypt [-apC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
639 [-o OUTPUT] [FILE]", "\
642 -a, --armour Same as `-f pem'.\n\
643 -f, --format=FORMAT Encode as FORMAT.\n\
644 -k, --key=TAG Use public encryption key named by TAG.\n\
645 -s, --sign-key=TAG Use private signature key named by TAG.\n\
646 -o, --output=FILE Write output to FILE.\n\
647 -p, --progress Show progress on large files.\n\
648 -C, --nocheck Don't check the public key.\n\
650 { "decrypt", decrypt,
651 "decrypt [-abpqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
654 -a, --armour Same as `-f pem'.\n\
655 -b, --buffer Buffer output until we're sure we have it all.\n\
656 -f, --format=FORMAT Decode as FORMAT.\n\
657 -o, --output=FILE Write output to FILE.\n\
658 -p, --progress Show progress on large files.\n\
659 -q, --quiet Produce fewer messages.\n\
660 -v, --verbose Produce more verbose messages.\n\
661 -C, --nocheck Don't check the private key.\n\
666 static int cmd_help(int argc, char **argv)
668 sc_help(cmdtab, stdout, argv + 1);
672 void version(FILE *fp)
674 pquis(fp, "$, Catacomb version " VERSION "\n");
677 static void usage(FILE *fp)
679 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
682 void help_global(FILE *fp)
686 Encrypt and decrypt files.\n\
688 Global command-line options:\n\
690 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
691 -v, --version Show program version number.\n\
692 -u, --usage Show a terse usage message.\n\
694 -k, --keyring=FILE Read keys from FILE.\n",
700 * Arguments: @int argc@ = number of command line arguments
701 * @char *argv[]@ = vector of command line arguments
703 * Returns: Zero if successful, nonzero otherwise.
705 * Use: Encrypts or decrypts files.
708 int main(int argc, char *argv[])
714 /* --- Initialize the library --- */
718 rand_noisesrc(RAND_GLOBAL, &noise_source);
719 rand_seed(RAND_GLOBAL, 160);
721 /* --- Parse options --- */
724 static struct option opts[] = {
725 { "help", 0, 0, 'h' },
726 { "version", 0, 0, 'v' },
727 { "usage", 0, 0, 'u' },
728 { "keyring", OPTF_ARGREQ, 0, 'k' },
731 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
736 sc_help(cmdtab, stdout, argv + optind);
758 if (f & f_bogus || argc < 1) {
763 /* --- Dispatch to the correct subcommand handler --- */
765 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
770 /*----- That's all, folks -------------------------------------------------*/