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>
56 /*----- Static variables --------------------------------------------------*/
58 static const char *keyring = "keyring";
60 /*----- Data format -------------------------------------------------------*/
64 * The encrypted message is divided into chunks, each preceded by a two-octet
65 * length. The chunks don't need to be large -- the idea is that we can
66 * stream the chunks in and out.
68 * The first chunk is a header. It contains the decryption key-id, and maybe
69 * the verification key-id if the message is signed.
71 * Next comes the key-encapsulation chunk. This is decrypted in some
72 * KEM-specific way to yield a secret hash. The hash is expanded using an
73 * MGF (or similar) to make a symmetric encryption and MAC key.
75 * If the message is signed, there comes a signature chunk. The signature is
76 * on the header and key-encapsulation chunks, and further output of the MGF.
77 * This means that the recipient can modify the message and still have a
78 * valid signature, so it's not useful for proving things to other people;
79 * but it also means that the recipient knows that the message is from
80 * someone who knows the hash, which limits the possiblities to (a) whoever
81 * encrypted the message (good!) and (b) whoever knows the recipient's
84 * Then come message chunks. Each one begins with a MAC over an implicit
85 * sequence number and the ciphertext. The final chunk's ciphertext is
86 * empty; no other chunk is empty. Thus can the correct end-of-file be
90 /*----- Chunk I/O ---------------------------------------------------------*/
92 static void chunk_write(enc *e, buf *b)
98 if (e->ops->write(e, l, 2) ||
99 e->ops->write(e, BBASE(b), BLEN(b)))
100 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
103 static void chunk_read(enc *e, dstr *d, buf *b)
110 if (e->ops->read(e, l, 2) != 2)
114 if (e->ops->read(e, d->buf, n) != n)
117 buf_init(b, d->buf, d->len);
121 if (!errno) die(EXIT_FAILURE, "unexpected end-of-file on input");
122 else die(EXIT_FAILURE, "error reading input: %s", strerror(errno));
125 /*----- Encryption --------------------------------------------------------*/
127 static int encrypt(int argc, char *argv[])
129 const char *fn, *of = 0, *kn = "ccrypt", *skn = 0;
132 const char *ef = "binary";
157 #define f_progress 4u
160 static const struct option opt[] = {
161 { "key", OPTF_ARGREQ, 0, 'k' },
162 { "sign-key", OPTF_ARGREQ, 0, 's' },
163 { "armour", 0, 0, 'a' },
164 { "armor", 0, 0, 'a' },
165 { "format", OPTF_ARGREQ, 0, 'f' },
166 { "output", OPTF_ARGREQ, 0, 'o' },
167 { "progress", 0, 0, 'p' },
168 { "nocheck", 0, 0, 'C' },
171 i = mdwopt(argc, argv, "k:s:af:o:pC", opt, 0, 0, 0);
174 case 'k': kn = optarg; break;
175 case 's': skn = optarg; break;
176 case 'a': ef = "pem"; break;
177 case 'f': ef = optarg; break;
178 case 'o': of = optarg; break;
179 case 'p': f |= f_progress; break;
180 case 'C': f |= f_nocheck; break;
181 default: f |= f_bogus; break;
184 if (argc - optind > 1 || (f & f_bogus))
185 die(EXIT_FAILURE, "Usage: encrypt [-OPTIONS] [FILE]");
187 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
188 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
189 if ((k = key_bytag(&kf, kn)) == 0)
190 die(EXIT_FAILURE, "key `%s' not found", kn);
191 if (skn && (sk = key_bytag(&kf, skn)) == 0)
192 die(EXIT_FAILURE, "key `%s' not found", skn);
194 if ((eo = getenc(ef)) == 0)
195 die(EXIT_FAILURE, "encoding `%s' not found", ef);
197 fn = optind < argc ? argv[optind++] : "-";
198 if (strcmp(fn, "-") == 0)
200 else if ((fp = fopen(fn, "rb")) == 0) {
201 die(EXIT_FAILURE, "couldn't open file `%s': %s",
202 fn, strerror(errno));
205 if (!of || strcmp(of, "-") == 0)
207 else if ((ofp = fopen(of, eo->wmode)) == 0) {
208 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
209 ofp, strerror(errno));
214 e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE");
215 km = getkem(k, "cckem", 0);
216 if (!(f & f_nocheck) && (err = km->ops->check(km)) != 0)
217 moan("key %s fails check: %s", d.buf, err);
221 s = getsig(sk, "ccsig", 1);
222 if ((err = s->ops->check(s)) != 0)
223 moan("key %s fails check: %s", d.buf, err);
226 /* --- Build the header chunk --- */
229 dstr_ensure(&d, 256);
230 buf_init(&b, d.buf, 256);
231 buf_putu32(&b, k->id);
232 if (sk) buf_putu32(&b, sk->id);
234 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
237 /* --- Build the KEM chunk --- */
240 if (setupkem(km, &d, &cx, &c, &m))
241 die(EXIT_FAILURE, "failed to encapsulate key");
242 buf_init(&b, d.buf, d.len);
244 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
247 /* --- Write the signature chunk --- */
250 GC_ENCRYPT(cx, 0, bb, 1024);
251 GH_HASH(s->h, bb, 1024);
253 if ((en = s->ops->doit(s, &d)) != 0)
254 die(EXIT_FAILURE, "error creating signature: %s", key_strerror(en));
255 buf_init(&b, d.buf, d.len);
260 /* --- Now do the main crypto --- */
262 if (f & f_progress) {
263 if (fprogress_init(&ff, fn, fp)) {
264 die(EXIT_FAILURE, "failed to initialize progress display: %s",
269 assert(GC_CLASS(c)->blksz <= sizeof(bb));
270 dstr_ensure(&d, sizeof(bb) + GM_CLASS(m)->hashsz);
272 chsz = MASK16 - GM_CLASS(m)->hashsz;
277 if (GC_CLASS(c)->blksz) {
278 GC_ENCRYPT(cx, 0, bb, GC_CLASS(c)->blksz);
281 n = fread(bb, 1, chsz, fp);
283 if (f & f_progress) fprogress_update(&ff, n);
284 buf_init(&b, d.buf, d.sz);
285 tag = buf_get(&b, GM_CLASS(m)->hashsz);
287 assert(tag); assert(ct);
288 GC_ENCRYPT(c, bb, ct, n);
295 /* --- Final terminator packet --- */
297 buf_init(&b, d.buf, d.sz);
298 tag = buf_get(&b, GM_CLASS(m)->hashsz);
304 /* --- All done --- */
306 if (f & f_progress) fprogress_done(&ff);
314 if (fp != stdin) fclose(fp);
325 /*---- Decryption ---------------------------------------------------------*/
327 static int decrypt(int argc, char *argv[])
329 const char *fn, *of = 0;
330 FILE *ofp = 0, *rfp = 0;
332 const char *ef = "binary";
359 #define f_progress 8u
362 static const struct option opt[] = {
363 { "armour", 0, 0, 'a' },
364 { "armor", 0, 0, 'a' },
365 { "buffer", 0, 0, 'b' },
366 { "verbose", 0, 0, 'v' },
367 { "quiet", 0, 0, 'q' },
368 { "nocheck", 0, 0, 'C' },
369 { "format", OPTF_ARGREQ, 0, 'f' },
370 { "output", OPTF_ARGREQ, 0, 'o' },
371 { "progress", 0, 0, 'p' },
374 i = mdwopt(argc, argv, "abf:o:pqvC", opt, 0, 0, 0);
377 case 'a': ef = "pem"; break;
378 case 'b': f |= f_buffer; break;
379 case 'v': verb++; break;
380 case 'q': if (verb) verb--; break;
381 case 'C': f |= f_nocheck; break;
382 case 'f': ef = optarg; break;
383 case 'o': of = optarg; break;
384 case 'p': f |= f_progress; break;
385 default: f |= f_bogus; break;
388 if (argc - optind > 1 || (f & f_bogus))
389 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
391 if ((eo = getenc(ef)) == 0)
392 die(EXIT_FAILURE, "encoding `%s' not found", ef);
394 fn = optind < argc ? argv[optind++] : "-";
395 if (strcmp(fn, "-") == 0)
397 else if ((fp = fopen(fn, eo->rmode)) == 0) {
398 die(EXIT_FAILURE, "couldn't open file `%s': %s",
399 fn, strerror(errno));
402 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
403 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
405 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
407 if (f & f_progress) {
408 if (fprogress_init(&ff, fn, fp)) {
409 die(EXIT_FAILURE, "failed to initialize progress display: %s",
414 /* --- Read the header chunk --- */
416 chunk_read(e, &d, &b);
418 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
419 if (buf_getu32(&b, &id)) {
420 if (f & f_progress) fprogress_done(&ff);
421 if (verb) printf("FAIL malformed header: missing keyid\n");
424 if ((k = key_byid(&kf, id)) == 0) {
425 if (f & f_progress) fprogress_done(&ff);
426 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
430 if (buf_getu32(&b, &id)) {
431 if (f & f_progress) fprogress_done(&ff);
432 if (verb) printf("FAIL malformed header: missing signature keyid\n");
435 if ((sk = key_byid(&kf, id)) == 0) {
436 if (f & f_progress) fprogress_done(&ff);
437 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
442 if (f & f_progress) fprogress_done(&ff);
443 if (verb) printf("FAIL malformed header: junk at end\n");
447 s = getsig(sk, "ccsig", 0);
448 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0) {
451 printf("WARN verification key %s fails check: %s\n", d.buf, err);
453 GH_HASHBUF16(s->h, BBASE(&b), BSZ(&b));
456 /* --- Find the key --- */
458 km = getkem(k, "cckem", 1);
460 /* --- Read the KEM chunk --- */
462 chunk_read(e, &d, &b);
464 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
465 if (setupkem(km, &d, &cx, &c, &m)) {
466 if (f & f_progress) fprogress_done(&ff);
467 if (verb) printf("FAIL failed to decapsulate key\n");
470 if (s) GH_HASHBUF16(s->h, d.buf, d.len);
472 /* --- Verify the signature, if there is one --- */
476 dstr_ensure(&d, 1024);
477 GC_ENCRYPT(cx, 0, d.buf, 1024);
478 GH_HASH(s->h, d.buf, 1024);
479 chunk_read(e, &d, &b);
481 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
482 if (s->ops->doit(s, &d)) {
483 if (f & f_progress) fprogress_done(&ff);
484 if (verb) printf("FAIL signature verification failed\n");
490 if (f & f_progress) fprogress_clear(&ff);
491 printf("INFO good-signature %s\n", d.buf);
495 if (f & f_progress) fprogress_clear(&ff);
496 printf("INFO no-signature\n");
499 /* --- Now decrypt the main body --- */
501 if (!of || strcmp(of, "-") == 0) {
505 if (!(f & f_buffer)) {
506 if ((ofp = fopen(of, "wb")) == 0) {
507 if (f & f_progress) fprogress_done(&ff);
508 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
509 ofp, strerror(errno));
512 } else if ((rfp = tmpfile()) == 0) {
513 if (f & f_progress) fprogress_done(&ff);
514 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
518 dstr_ensure(&d, GC_CLASS(c)->blksz);
521 if (GC_CLASS(c)->blksz) {
522 GC_ENCRYPT(cx, 0, d.buf, GC_CLASS(c)->blksz);
528 chunk_read(e, &d, &b);
530 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
531 if ((tag = buf_get(&b, GM_CLASS(m)->hashsz)) == 0) {
532 if (f & f_progress) fprogress_done(&ff);
533 if (verb) printf("FAIL bad ciphertext chunk: no tag\n");
536 GH_HASH(h, BCUR(&b), BLEFT(&b));
537 if (memcmp(tag, GH_DONE(h, 0), GM_CLASS(m)->hashsz) != 0) {
538 if (f & f_progress) fprogress_done(&ff);
540 printf("FAIL bad ciphertext chunk: authentication failure\n");
546 GC_DECRYPT(c, BCUR(&b), BCUR(&b), BLEFT(&b));
547 if (fwrite(BCUR(&b), 1, BLEFT(&b), rfp) != BLEFT(&b)) {
548 if (f & f_progress) fprogress_done(&ff);
549 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
554 if (f & f_progress) fprogress_done(&ff);
555 if (fflush(rfp) || ferror(rfp)) {
556 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
560 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
561 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
562 of, strerror(errno));
565 if (f & f_progress) fprogress_init(&ff, "copying buffer", rfp);
567 dstr_ensure(&d, 65536);
568 if (verb && ofp == stdout) printf("DATA\n");
570 n = fread(d.buf, 1, d.sz, rfp);
572 if (f & f_progress) fprogress_update(&ff, n);
573 if (fwrite(d.buf, 1, n, ofp) < n) {
574 if (f & f_progress) fprogress_done(&ff);
575 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
578 if (f & f_progress) fprogress_done(&ff);
579 if (ferror(rfp) || fclose(rfp))
580 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
584 if (verb && ofp != stdout)
585 printf("OK decrypted successfully\n");
586 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
587 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
593 if (fp != stdin) fclose(fp);
604 /*----- Main code ---------------------------------------------------------*/
608 listtab[i].name, listtab[i].name) \
609 LI("Key-encapsulation mechanisms", kem, \
610 kemtab[i].name, kemtab[i].name) \
611 LI("Signature schemes", sig, \
612 sigtab[i].name, sigtab[i].name) \
613 LI("Encodings", enc, \
614 enctab[i].name, enctab[i].name) \
615 LI("Symmetric encryption algorithms", cipher, \
616 gciphertab[i], gciphertab[i]->name) \
617 LI("Hash functions", hash, \
618 ghashtab[i], ghashtab[i]->name) \
619 LI("Message authentication codes", mac, \
620 gmactab[i], gmactab[i]->name)
622 MAKELISTTAB(listtab, LISTS)
624 int cmd_show(int argc, char *argv[])
626 return (displaylists(listtab, argv + 1));
629 static int cmd_help(int, char **);
631 static cmd cmdtab[] = {
632 { "help", cmd_help, "help [COMMAND...]" },
633 { "show", cmd_show, "show [ITEM...]" },
636 { "encrypt", encrypt,
637 "encrypt [-apC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
638 [-o OUTPUT] [FILE]", "\
641 -a, --armour Same as `-f pem'.\n\
642 -f, --format=FORMAT Encode as FORMAT.\n\
643 -k, --key=TAG Use public encryption key named by TAG.\n\
644 -s, --sign-key=TAG Use private signature key named by TAG.\n\
645 -o, --output=FILE Write output to FILE.\n\
646 -p, --progress Show progress on large files.\n\
647 -C, --nocheck Don't check the public key.\n\
649 { "decrypt", decrypt,
650 "decrypt [-abpqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
653 -a, --armour Same as `-f pem'.\n\
654 -b, --buffer Buffer output until we're sure we have it all.\n\
655 -f, --format=FORMAT Decode as FORMAT.\n\
656 -o, --output=FILE Write output to FILE.\n\
657 -p, --progress Show progress on large files.\n\
658 -q, --quiet Produce fewer messages.\n\
659 -v, --verbose Produce more verbose messages.\n\
660 -C, --nocheck Don't check the private key.\n\
665 static int cmd_help(int argc, char **argv)
667 sc_help(cmdtab, stdout, argv + 1);
671 void version(FILE *fp)
673 pquis(fp, "$, Catacomb version " VERSION "\n");
676 static void usage(FILE *fp)
678 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
681 void help_global(FILE *fp)
685 Encrypt and decrypt files.\n\
687 Global command-line options:\n\
689 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
690 -v, --version Show program version number.\n\
691 -u, --usage Show a terse usage message.\n\
693 -k, --keyring=FILE Read keys from FILE.\n",
699 * Arguments: @int argc@ = number of command line arguments
700 * @char *argv[]@ = vector of command line arguments
702 * Returns: Zero if successful, nonzero otherwise.
704 * Use: Encrypts or decrypts files.
707 int main(int argc, char *argv[])
713 /* --- Initialize the library --- */
717 rand_noisesrc(RAND_GLOBAL, &noise_source);
718 rand_seed(RAND_GLOBAL, 160);
720 /* --- Parse options --- */
723 static struct option opts[] = {
724 { "help", 0, 0, 'h' },
725 { "version", 0, 0, 'v' },
726 { "usage", 0, 0, 'u' },
727 { "keyring", OPTF_ARGREQ, 0, 'k' },
730 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
735 sc_help(cmdtab, stdout, argv + optind);
757 if (f & f_bogus || argc < 1) {
762 /* --- Dispatch to the correct subcommand handler --- */
764 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
769 /*----- That's all, folks -------------------------------------------------*/