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>
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";
156 #define f_progress 4u
159 static const struct option opt[] = {
160 { "key", OPTF_ARGREQ, 0, 'k' },
161 { "sign-key", OPTF_ARGREQ, 0, 's' },
162 { "armour", 0, 0, 'a' },
163 { "armor", 0, 0, 'a' },
164 { "format", OPTF_ARGREQ, 0, 'f' },
165 { "output", OPTF_ARGREQ, 0, 'o' },
166 { "progress", 0, 0, 'p' },
167 { "nocheck", 0, 0, 'C' },
170 i = mdwopt(argc, argv, "k:s:af:o:pC", opt, 0, 0, 0);
173 case 'k': kn = optarg; break;
174 case 's': skn = optarg; break;
175 case 'a': ef = "pem"; break;
176 case 'f': ef = optarg; break;
177 case 'o': of = optarg; break;
178 case 'p': f |= f_progress; break;
179 case 'C': f |= f_nocheck; break;
180 default: f |= f_bogus; break;
183 if (argc - optind > 1 || (f & f_bogus))
184 die(EXIT_FAILURE, "Usage: encrypt [-OPTIONS] [FILE]");
186 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
187 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
188 if ((k = key_bytag(&kf, kn)) == 0)
189 die(EXIT_FAILURE, "key `%s' not found", kn);
190 if (skn && (sk = key_bytag(&kf, skn)) == 0)
191 die(EXIT_FAILURE, "key `%s' not found", skn);
193 if ((eo = getenc(ef)) == 0)
194 die(EXIT_FAILURE, "encoding `%s' not found", ef);
196 fn = optind < argc ? argv[optind++] : "-";
197 if (strcmp(fn, "-") == 0)
199 else if ((fp = fopen(fn, "rb")) == 0) {
200 die(EXIT_FAILURE, "couldn't open file `%s': %s",
201 fn, strerror(errno));
204 if (!of || strcmp(of, "-") == 0)
206 else if ((ofp = fopen(of, eo->wmode)) == 0) {
207 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
208 of, strerror(errno));
213 e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE");
214 km = getkem(k, "cckem", 0, &bc);
215 if (!(f & f_nocheck) && (err = km->ops->check(km)) != 0)
216 moan("key %s fails check: %s", d.buf, err);
220 s = getsig(sk, "ccsig", 1);
221 if ((err = s->ops->check(s)) != 0)
222 moan("key %s fails check: %s", d.buf, err);
225 /* --- Build the header chunk --- */
228 dstr_ensure(&d, 256);
229 buf_init(&b, d.buf, 256);
230 buf_putu32(&b, k->id);
231 if (sk) buf_putu32(&b, sk->id);
233 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
236 /* --- Build the KEM chunk --- */
239 if (setupkem(km, &d, bc)) die(EXIT_FAILURE, "failed to encapsulate key");
240 buf_init(&b, d.buf, d.len);
242 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
245 /* --- Write the signature chunk --- */
248 GC_ENCRYPT(km->cx, 0, bb, 1024);
249 GH_HASH(s->h, bb, 1024);
251 if ((en = s->ops->doit(s, &d)) != 0)
252 die(EXIT_FAILURE, "error creating signature: %s", key_strerror(en));
253 buf_init(&b, d.buf, d.len);
258 /* --- Now do the main crypto --- */
260 if (f & f_progress) {
261 if (fprogress_init(&ff, fn, fp)) {
262 die(EXIT_FAILURE, "failed to initialize progress display: %s",
267 n = bc->ops->overhead(bc);
268 dstr_ensure(&d, sizeof(bb) + n);
272 n = fread(bb, 1, chsz, fp);
273 if (f & f_progress) fprogress_update(&ff, n);
274 buf_init(&b, d.buf, d.sz);
275 if ((err = bc->ops->doit(bc, seq, &b, bb, n)) != 0) {
276 if (f & f_progress) fprogress_done(&ff);
277 die(EXIT_FAILURE, "failed to encrypt packet: %s\n", err);
283 /* --- All done --- */
285 if (f & f_progress) fprogress_done(&ff);
287 bc->ops->destroy(bc);
291 if (fp != stdin) fclose(fp);
302 /*---- Decryption ---------------------------------------------------------*/
304 static int decrypt(int argc, char *argv[])
306 const char *fn, *of = 0;
307 FILE *ofp = 0, *rfp = 0;
309 const char *ef = "binary";
333 #define f_progress 8u
336 static const struct option opt[] = {
337 { "armour", 0, 0, 'a' },
338 { "armor", 0, 0, 'a' },
339 { "buffer", 0, 0, 'b' },
340 { "verbose", 0, 0, 'v' },
341 { "quiet", 0, 0, 'q' },
342 { "nocheck", 0, 0, 'C' },
343 { "format", OPTF_ARGREQ, 0, 'f' },
344 { "output", OPTF_ARGREQ, 0, 'o' },
345 { "progress", 0, 0, 'p' },
348 i = mdwopt(argc, argv, "abf:o:pqvC", opt, 0, 0, 0);
351 case 'a': ef = "pem"; break;
352 case 'b': f |= f_buffer; break;
353 case 'v': verb++; break;
354 case 'q': if (verb) verb--; break;
355 case 'C': f |= f_nocheck; break;
356 case 'f': ef = optarg; break;
357 case 'o': of = optarg; break;
358 case 'p': f |= f_progress; break;
359 default: f |= f_bogus; break;
362 if (argc - optind > 1 || (f & f_bogus))
363 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
365 if ((eo = getenc(ef)) == 0)
366 die(EXIT_FAILURE, "encoding `%s' not found", ef);
368 fn = optind < argc ? argv[optind++] : "-";
369 if (strcmp(fn, "-") == 0)
371 else if ((fp = fopen(fn, eo->rmode)) == 0) {
372 die(EXIT_FAILURE, "couldn't open file `%s': %s",
373 fn, strerror(errno));
376 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
377 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
379 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
381 if (f & f_progress) {
382 if (fprogress_init(&ff, fn, fp)) {
383 die(EXIT_FAILURE, "failed to initialize progress display: %s",
388 /* --- Read the header chunk --- */
390 chunk_read(e, &d, &b);
392 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
393 if (buf_getu32(&b, &id)) {
394 if (f & f_progress) fprogress_done(&ff);
395 if (verb) printf("FAIL malformed header: missing keyid\n");
398 if ((k = key_byid(&kf, id)) == 0) {
399 if (f & f_progress) fprogress_done(&ff);
400 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
404 if (buf_getu32(&b, &id)) {
405 if (f & f_progress) fprogress_done(&ff);
406 if (verb) printf("FAIL malformed header: missing signature keyid\n");
409 if ((sk = key_byid(&kf, id)) == 0) {
410 if (f & f_progress) fprogress_done(&ff);
411 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
416 if (f & f_progress) fprogress_done(&ff);
417 if (verb) printf("FAIL malformed header: junk at end\n");
421 s = getsig(sk, "ccsig", 0);
422 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0) {
425 printf("WARN verification key %s fails check: %s\n", d.buf, err);
427 GH_HASHBUF16(s->h, BBASE(&b), BSZ(&b));
430 /* --- Find the key --- */
432 km = getkem(k, "cckem", 1, &bc);
434 /* --- Read the KEM chunk --- */
436 chunk_read(e, &d, &b);
438 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
439 if (setupkem(km, &d, bc)) {
440 if (f & f_progress) fprogress_done(&ff);
441 if (verb) printf("FAIL failed to decapsulate key\n");
444 if (s) GH_HASHBUF16(s->h, d.buf, d.len);
446 /* --- Verify the signature, if there is one --- */
450 dstr_ensure(&d, 1024);
451 GC_ENCRYPT(km->cx, 0, d.buf, 1024);
452 GH_HASH(s->h, d.buf, 1024);
453 chunk_read(e, &d, &b);
455 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
456 if (s->ops->doit(s, &d)) {
457 if (f & f_progress) fprogress_done(&ff);
458 if (verb) printf("FAIL signature verification failed\n");
464 if (f & f_progress) fprogress_clear(&ff);
465 printf("INFO good-signature %s\n", d.buf);
469 if (f & f_progress) fprogress_clear(&ff);
470 printf("INFO no-signature\n");
473 /* --- Now decrypt the main body --- */
475 if (!of || strcmp(of, "-") == 0) {
479 if (!(f & f_buffer)) {
480 if ((ofp = fopen(of, "wb")) == 0) {
481 if (f & f_progress) fprogress_done(&ff);
482 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
483 of, strerror(errno));
486 } else if ((rfp = tmpfile()) == 0) {
487 if (f & f_progress) fprogress_done(&ff);
488 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
492 dstr_ensure(&d, bc->ops->overhead(bc));
495 chunk_read(e, &d, &b);
497 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
498 buf_init(&b, bb, sizeof(bb));
499 if ((err = bc->ops->doit(bc, seq, &b, d.buf, d.len)) != 0) {
500 if (f & f_progress) fprogress_done(&ff);
501 if (verb) printf("FAIL bad ciphertext chunk: %s\n", err);
505 if (!BLEN(&b)) break;
506 if (fwrite(BBASE(&b), 1, BLEN(&b), rfp) != BLEN(&b)) {
507 if (f & f_progress) fprogress_done(&ff);
508 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
513 if (f & f_progress) fprogress_done(&ff);
514 if (fflush(rfp) || ferror(rfp)) {
515 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
519 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
520 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
521 of, strerror(errno));
524 if (f & f_progress) fprogress_init(&ff, "copying buffer", rfp);
526 dstr_ensure(&d, 65536);
527 if (verb && ofp == stdout) printf("DATA\n");
529 n = fread(d.buf, 1, d.sz, rfp);
531 if (f & f_progress) fprogress_update(&ff, n);
532 if (fwrite(d.buf, 1, n, ofp) < n) {
533 if (f & f_progress) fprogress_done(&ff);
534 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
537 if (f & f_progress) fprogress_done(&ff);
538 if (ferror(rfp) || fclose(rfp))
539 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
543 if (verb && ofp != stdout)
544 printf("OK decrypted successfully\n");
545 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
546 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
547 bc->ops->destroy(bc);
550 if (fp != stdin) fclose(fp);
561 /*----- Main code ---------------------------------------------------------*/
565 listtab[i].name, listtab[i].name) \
566 LI("Key-encapsulation mechanisms", kem, \
567 kemtab[i].name, kemtab[i].name) \
568 LI("Bulk crypto transforms", bulk, \
569 bulktab[i].name, bulktab[i].name) \
570 LI("Signature schemes", sig, \
571 sigtab[i].name, sigtab[i].name) \
572 LI("Encodings", enc, \
573 enctab[i].name, enctab[i].name) \
574 LI("Symmetric encryption algorithms", cipher, \
575 gciphertab[i], gciphertab[i]->name) \
576 LI("Authenticated encryption schemes", aead, \
577 gaeadtab[i], gaeadtab[i]->name) \
578 LI("Hash functions", hash, \
579 ghashtab[i], ghashtab[i]->name) \
580 LI("Message authentication codes", mac, \
581 gmactab[i], gmactab[i]->name)
583 MAKELISTTAB(listtab, LISTS)
585 int cmd_show(int argc, char *argv[])
587 return (displaylists(listtab, argv + 1));
590 static int cmd_help(int, char **);
592 static cmd cmdtab[] = {
593 { "help", cmd_help, "help [COMMAND...]" },
594 { "show", cmd_show, "show [ITEM...]" },
597 { "encrypt", encrypt,
598 "encrypt [-apC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
599 [-o OUTPUT] [FILE]", "\
602 -a, --armour Same as `-f pem'.\n\
603 -f, --format=FORMAT Encode as FORMAT.\n\
604 -k, --key=TAG Use public encryption key named by TAG.\n\
605 -s, --sign-key=TAG Use private signature key named by TAG.\n\
606 -o, --output=FILE Write output to FILE.\n\
607 -p, --progress Show progress on large files.\n\
608 -C, --nocheck Don't check the public key.\n\
610 { "decrypt", decrypt,
611 "decrypt [-abpqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
614 -a, --armour Same as `-f pem'.\n\
615 -b, --buffer Buffer output until we're sure we have it all.\n\
616 -f, --format=FORMAT Decode as FORMAT.\n\
617 -o, --output=FILE Write output to FILE.\n\
618 -p, --progress Show progress on large files.\n\
619 -q, --quiet Produce fewer messages.\n\
620 -v, --verbose Produce more verbose messages.\n\
621 -C, --nocheck Don't check the private key.\n\
626 static int cmd_help(int argc, char **argv)
628 sc_help(cmdtab, stdout, argv + 1);
632 void version(FILE *fp)
634 pquis(fp, "$, Catacomb version " VERSION "\n");
637 static void usage(FILE *fp)
639 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
642 void help_global(FILE *fp)
646 Encrypt and decrypt files.\n\
648 Global command-line options:\n\
650 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
651 -v, --version Show program version number.\n\
652 -u, --usage Show a terse usage message.\n\
654 -k, --keyring=FILE Read keys from FILE.\n",
660 * Arguments: @int argc@ = number of command line arguments
661 * @char *argv[]@ = vector of command line arguments
663 * Returns: Zero if successful, nonzero otherwise.
665 * Use: Encrypts or decrypts files.
668 int main(int argc, char *argv[])
674 /* --- Initialize the library --- */
678 rand_noisesrc(RAND_GLOBAL, &noise_source);
679 rand_seed(RAND_GLOBAL, 160);
681 /* --- Parse options --- */
684 static struct option opts[] = {
685 { "help", 0, 0, 'h' },
686 { "version", 0, 0, 'v' },
687 { "usage", 0, 0, 'u' },
688 { "keyring", OPTF_ARGREQ, 0, 'k' },
691 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
696 sc_help(cmdtab, stdout, argv + optind);
718 if (f & f_bogus || argc < 1) {
723 /* --- Dispatch to the correct subcommand handler --- */
725 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
730 /*----- That's all, folks -------------------------------------------------*/