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/macros.h>
42 #include <mLib/mdwopt.h>
43 #include <mLib/quis.h>
44 #include <mLib/report.h>
59 /*----- Static variables --------------------------------------------------*/
61 static const char *keyring = "keyring";
63 /*----- Data format -------------------------------------------------------*/
67 * The encrypted message is divided into chunks, each preceded by a two-octet
68 * length. The chunks don't need to be large -- the idea is that we can
69 * stream the chunks in and out.
71 * The first chunk is a header. It contains the decryption key-id, and maybe
72 * the verification key-id if the message is signed.
74 * Next comes the key-encapsulation chunk. This is decrypted in some
75 * KEM-specific way to yield a secret hash. The hash is expanded using an
76 * MGF (or similar) to make a symmetric encryption and MAC key.
78 * If the message is signed, there comes a signature chunk. The signature is
79 * on the header and key-encapsulation chunks, and further output of the MGF.
80 * This means that the recipient can modify the message and still have a
81 * valid signature, so it's not useful for proving things to other people;
82 * but it also means that the recipient knows that the message is from
83 * someone who knows the hash, which limits the possiblities to (a) whoever
84 * encrypted the message (good!) and (b) whoever knows the recipient's
87 * Then come message chunks. Each one begins with a MAC over an implicit
88 * sequence number and the ciphertext. The final chunk's ciphertext is
89 * empty; no other chunk is empty. Thus can the correct end-of-file be
93 /*----- Chunk I/O ---------------------------------------------------------*/
95 static void chunk_write(enc *e, buf *b)
101 if (e->ops->write(e, l, 2) ||
102 e->ops->write(e, BBASE(b), BLEN(b)))
103 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
106 static void chunk_read(enc *e, dstr *d, buf *b)
113 if (e->ops->read(e, l, 2) != 2)
117 if (e->ops->read(e, d->buf, n) != n)
120 buf_init(b, d->buf, d->len);
124 if (!errno) die(EXIT_FAILURE, "unexpected end-of-file on input");
125 else die(EXIT_FAILURE, "error reading input: %s", strerror(errno));
128 /*----- Encryption --------------------------------------------------------*/
130 static int encrypt(int argc, char *argv[])
132 const char *fn, *of = 0, *kn = "ccrypt", *skn = 0;
135 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, ==, "-"))
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, ==, "-"))
207 else if ((ofp = fopen(of, eo->wmode)) == 0) {
208 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
209 of, strerror(errno));
214 e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE");
215 km = getkem(k, "cckem", 0, &bc);
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, bc)) die(EXIT_FAILURE, "failed to encapsulate key");
241 buf_init(&b, d.buf, d.len);
243 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
246 /* --- Write the signature chunk --- */
249 GC_ENCRYPT(km->cx, 0, bb, 1024);
250 GH_HASH(s->h, bb, 1024);
252 if ((en = s->ops->doit(s, &d)) != 0)
253 die(EXIT_FAILURE, "error creating signature: %s", key_strerror(en));
254 buf_init(&b, d.buf, d.len);
259 /* --- Now do the main crypto --- */
261 if (f & f_progress) {
262 if (fprogress_init(&ff, fn, fp)) {
263 die(EXIT_FAILURE, "failed to initialize progress display: %s",
268 n = bc->ops->overhead(bc);
269 dstr_ensure(&d, sizeof(bb) + n);
273 n = fread(bb, 1, chsz, fp);
274 if (f & f_progress) fprogress_update(&ff, n);
275 buf_init(&b, d.buf, d.sz);
276 if ((err = bc->ops->doit(bc, seq, &b, bb, n)) != 0) {
277 if (f & f_progress) fprogress_done(&ff);
278 die(EXIT_FAILURE, "failed to encrypt packet: %s\n", err);
284 /* --- All done --- */
286 if (f & f_progress) fprogress_done(&ff);
288 bc->ops->destroy(bc);
292 if (fp != stdin) fclose(fp);
303 /*---- Decryption ---------------------------------------------------------*/
305 static int decrypt(int argc, char *argv[])
307 const char *fn, *of = 0;
308 FILE *ofp = 0, *rfp = 0;
310 const char *ef = "binary";
334 #define f_progress 8u
337 static const struct option opt[] = {
338 { "armour", 0, 0, 'a' },
339 { "armor", 0, 0, 'a' },
340 { "buffer", 0, 0, 'b' },
341 { "verbose", 0, 0, 'v' },
342 { "quiet", 0, 0, 'q' },
343 { "nocheck", 0, 0, 'C' },
344 { "format", OPTF_ARGREQ, 0, 'f' },
345 { "output", OPTF_ARGREQ, 0, 'o' },
346 { "progress", 0, 0, 'p' },
349 i = mdwopt(argc, argv, "abf:o:pqvC", opt, 0, 0, 0);
352 case 'a': ef = "pem"; break;
353 case 'b': f |= f_buffer; break;
354 case 'v': verb++; break;
355 case 'q': if (verb) verb--; break;
356 case 'C': f |= f_nocheck; break;
357 case 'f': ef = optarg; break;
358 case 'o': of = optarg; break;
359 case 'p': f |= f_progress; break;
360 default: f |= f_bogus; break;
363 if (argc - optind > 1 || (f & f_bogus))
364 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
366 if ((eo = getenc(ef)) == 0)
367 die(EXIT_FAILURE, "encoding `%s' not found", ef);
369 fn = optind < argc ? argv[optind++] : "-";
370 if (STRCMP(fn, ==, "-"))
372 else if ((fp = fopen(fn, eo->rmode)) == 0) {
373 die(EXIT_FAILURE, "couldn't open file `%s': %s",
374 fn, strerror(errno));
377 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
378 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
380 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
382 if (f & f_progress) {
383 if (fprogress_init(&ff, fn, fp)) {
384 die(EXIT_FAILURE, "failed to initialize progress display: %s",
389 /* --- Read the header chunk --- */
391 chunk_read(e, &d, &b);
393 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
394 if (buf_getu32(&b, &id)) {
395 if (f & f_progress) fprogress_done(&ff);
396 if (verb) printf("FAIL malformed header: missing keyid\n");
399 if ((k = key_byid(&kf, id)) == 0) {
400 if (f & f_progress) fprogress_done(&ff);
401 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
405 if (buf_getu32(&b, &id)) {
406 if (f & f_progress) fprogress_done(&ff);
407 if (verb) printf("FAIL malformed header: missing signature keyid\n");
410 if ((sk = key_byid(&kf, id)) == 0) {
411 if (f & f_progress) fprogress_done(&ff);
412 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
417 if (f & f_progress) fprogress_done(&ff);
418 if (verb) printf("FAIL malformed header: junk at end\n");
422 s = getsig(sk, "ccsig", 0);
423 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0) {
426 printf("WARN verification key %s fails check: %s\n", d.buf, err);
428 GH_HASHBUF16(s->h, BBASE(&b), BSZ(&b));
431 /* --- Find the key --- */
433 km = getkem(k, "cckem", 1, &bc);
435 /* --- Read the KEM chunk --- */
437 chunk_read(e, &d, &b);
439 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
440 if (setupkem(km, &d, bc)) {
441 if (f & f_progress) fprogress_done(&ff);
442 if (verb) printf("FAIL failed to decapsulate key\n");
445 if (s) GH_HASHBUF16(s->h, d.buf, d.len);
447 /* --- Verify the signature, if there is one --- */
451 dstr_ensure(&d, 1024);
452 GC_ENCRYPT(km->cx, 0, d.buf, 1024);
453 GH_HASH(s->h, d.buf, 1024);
454 chunk_read(e, &d, &b);
456 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
457 if (s->ops->doit(s, &d)) {
458 if (f & f_progress) fprogress_done(&ff);
459 if (verb) printf("FAIL signature verification failed\n");
465 if (f & f_progress) fprogress_clear(&ff);
466 printf("INFO good-signature %s\n", d.buf);
470 if (f & f_progress) fprogress_clear(&ff);
471 printf("INFO no-signature\n");
474 /* --- Now decrypt the main body --- */
476 if (!of || STRCMP(of, ==, "-")) {
480 if (!(f & f_buffer)) {
481 if ((ofp = fopen(of, "wb")) == 0) {
482 if (f & f_progress) fprogress_done(&ff);
483 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
484 of, strerror(errno));
487 } else if ((rfp = tmpfile()) == 0) {
488 if (f & f_progress) fprogress_done(&ff);
489 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
493 dstr_ensure(&d, bc->ops->overhead(bc));
496 chunk_read(e, &d, &b);
498 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
499 buf_init(&b, bb, sizeof(bb));
500 if ((err = bc->ops->doit(bc, seq, &b, d.buf, d.len)) != 0) {
501 if (f & f_progress) fprogress_done(&ff);
502 if (verb) printf("FAIL bad ciphertext chunk: %s\n", err);
506 if (!BLEN(&b)) break;
507 if (fwrite(BBASE(&b), 1, BLEN(&b), rfp) != BLEN(&b)) {
508 if (f & f_progress) fprogress_done(&ff);
509 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
514 if (f & f_progress) fprogress_done(&ff);
515 if (fflush(rfp) || ferror(rfp)) {
516 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
520 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
521 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
522 of, strerror(errno));
525 if (f & f_progress) fprogress_init(&ff, "copying buffer", rfp);
527 dstr_ensure(&d, 65536);
528 if (verb && ofp == stdout) printf("DATA\n");
530 n = fread(d.buf, 1, d.sz, rfp);
532 if (f & f_progress) fprogress_update(&ff, n);
533 if (fwrite(d.buf, 1, n, ofp) < n) {
534 if (f & f_progress) fprogress_done(&ff);
535 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
538 if (f & f_progress) fprogress_done(&ff);
539 if (ferror(rfp) || fclose(rfp))
540 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
544 if (verb && ofp != stdout)
545 printf("OK decrypted successfully\n");
546 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
547 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
548 bc->ops->destroy(bc);
551 if (fp != stdin) fclose(fp);
562 /*----- Main code ---------------------------------------------------------*/
566 listtab[i].name, listtab[i].name) \
567 LI("Key-encapsulation mechanisms", kem, \
568 kemtab[i].name, kemtab[i].name) \
569 LI("Bulk crypto transforms", bulk, \
570 bulktab[i].name, bulktab[i].name) \
571 LI("Signature schemes", sig, \
572 sigtab[i].name, sigtab[i].name) \
573 LI("Encodings", enc, \
574 enctab[i].name, enctab[i].name) \
575 LI("Symmetric encryption algorithms", cipher, \
576 gciphertab[i], gciphertab[i]->name) \
577 LI("Authenticated encryption schemes", aead, \
578 gaeadtab[i], gaeadtab[i]->name) \
579 LI("Hash functions", hash, \
580 ghashtab[i], ghashtab[i]->name) \
581 LI("Message authentication codes", mac, \
582 gmactab[i], gmactab[i]->name)
584 MAKELISTTAB(listtab, LISTS)
586 int cmd_show(int argc, char *argv[])
588 return (displaylists(listtab, argv + 1));
591 static int cmd_help(int, char **);
593 static cmd cmdtab[] = {
594 { "help", cmd_help, "help [COMMAND...]" },
595 { "show", cmd_show, "show [ITEM...]" },
598 { "encrypt", encrypt,
599 "encrypt [-apC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
600 [-o OUTPUT] [FILE]", "\
603 -a, --armour Same as `-f pem'.\n\
604 -f, --format=FORMAT Encode as FORMAT.\n\
605 -k, --key=TAG Use public encryption key named by TAG.\n\
606 -s, --sign-key=TAG Use private signature key named by TAG.\n\
607 -o, --output=FILE Write output to FILE.\n\
608 -p, --progress Show progress on large files.\n\
609 -C, --nocheck Don't check the public key.\n\
611 { "decrypt", decrypt,
612 "decrypt [-abpqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
615 -a, --armour Same as `-f pem'.\n\
616 -b, --buffer Buffer output until we're sure we have it all.\n\
617 -f, --format=FORMAT Decode as FORMAT.\n\
618 -o, --output=FILE Write output to FILE.\n\
619 -p, --progress Show progress on large files.\n\
620 -q, --quiet Produce fewer messages.\n\
621 -v, --verbose Produce more verbose messages.\n\
622 -C, --nocheck Don't check the private key.\n\
627 static int cmd_help(int argc, char **argv)
629 sc_help(cmdtab, stdout, argv + 1);
633 void version(FILE *fp)
635 pquis(fp, "$, Catacomb version " VERSION "\n");
638 static void usage(FILE *fp)
640 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
643 void help_global(FILE *fp)
647 Encrypt and decrypt files.\n\
649 Global command-line options:\n\
651 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
652 -v, --version Show program version number.\n\
653 -u, --usage Show a terse usage message.\n\
655 -k, --keyring=FILE Read keys from FILE.\n",
661 * Arguments: @int argc@ = number of command line arguments
662 * @char *argv[]@ = vector of command line arguments
664 * Returns: Zero if successful, nonzero otherwise.
666 * Use: Encrypts or decrypts files.
669 int main(int argc, char *argv[])
675 /* --- Initialize the library --- */
679 rand_noisesrc(RAND_GLOBAL, &noise_source);
680 rand_seed(RAND_GLOBAL, 160);
682 /* --- Parse options --- */
685 static struct option opts[] = {
686 { "help", 0, 0, 'h' },
687 { "version", 0, 0, 'v' },
688 { "usage", 0, 0, 'u' },
689 { "keyring", OPTF_ARGREQ, 0, 'k' },
692 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
697 sc_help(cmdtab, stdout, argv + optind);
719 if (f & f_bogus || argc < 1) {
724 /* --- Dispatch to the correct subcommand handler --- */
726 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
731 /*----- That's all, folks -------------------------------------------------*/