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 ------------------------------------------------------*/
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 /*----- Utilities ---------------------------------------------------------*/
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 further output of the MGF. This means that the recipient can
79 * modify the message and still have a valid signature, so it's not useful
80 * for proving things to other people; but it also means that the recipient
81 * knows that the message is from someone who knows the hash, which limits
82 * the possiblities to (a) whoever encrypted the message (good!) and (b)
83 * whoever knows the recipient's private key.
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 *of = 0, *kn = "ccrypt", *skn = 0;
133 const char *ef = "binary";
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 { "nocheck", 0, 0, 'C' },
169 i = mdwopt(argc, argv, "k:s:af:o:C", opt, 0, 0, 0);
172 case 'k': kn = optarg; break;
173 case 's': skn = optarg; break;
174 case 'a': ef = "pem"; break;
175 case 'f': ef = optarg; break;
176 case 'o': of = optarg; break;
177 case 'C': f |= f_nocheck; break;
178 default: f |= f_bogus; break;
181 if (argc - optind > 1 || (f & f_bogus))
182 die(EXIT_FAILURE, "Usage: encrypt [-OPTIONS] [FILE]");
184 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
185 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
186 if ((k = key_bytag(&kf, kn)) == 0)
187 die(EXIT_FAILURE, "key `%s' not found", kn);
188 if (skn && (sk = key_bytag(&kf, skn)) == 0)
189 die(EXIT_FAILURE, "key `%s' not found", skn);
191 if ((eo = getenc(ef)) == 0)
192 die(EXIT_FAILURE, "encoding `%s' not found", ef);
196 else if (strcmp(argv[optind], "-") == 0) {
199 } else if ((fp = fopen(argv[optind], "rb")) == 0) {
200 die(EXIT_FAILURE, "couldn't open file `%s': %s",
201 argv[optind], 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);
236 /* --- Build the KEM chunk --- */
239 if (setupkem(km, &d, &cx, &c, &m))
240 die(EXIT_FAILURE, "failed to encapsulate key");
241 buf_init(&b, d.buf, d.len);
245 /* --- Write the signature chunk --- */
248 GC_ENCRYPT(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 assert(GC_CLASS(c)->blksz <= sizeof(bb));
261 dstr_ensure(&d, sizeof(bb) + GM_CLASS(m)->hashsz);
267 if (GC_CLASS(c)->blksz) {
268 GC_ENCRYPT(cx, 0, bb, GC_CLASS(c)->blksz);
271 n = fread(bb, 1, sizeof(bb), fp);
273 buf_init(&b, d.buf, d.sz);
274 tag = buf_get(&b, GM_CLASS(m)->hashsz);
276 assert(tag); assert(ct);
277 GC_ENCRYPT(c, bb, ct, n);
284 /* --- Final terminator packet --- */
286 buf_init(&b, d.buf, d.sz);
287 tag = buf_get(&b, GM_CLASS(m)->hashsz);
293 /* --- All done --- */
302 if (fp != stdin) fclose(fp);
312 /*---- Decryption ---------------------------------------------------------*/
314 static int decrypt(int argc, char *argv[])
317 FILE *ofp = 0, *rfp = 0;
319 const char *ef = "binary";
347 static const struct option opt[] = {
348 { "armour", 0, 0, 'a' },
349 { "armor", 0, 0, 'a' },
350 { "buffer", 0, 0, 'b' },
351 { "verbose", 0, 0, 'v' },
352 { "quiet", 0, 0, 'q' },
353 { "nocheck", 0, 0, 'C' },
354 { "format", OPTF_ARGREQ, 0, 'f' },
355 { "output", OPTF_ARGREQ, 0, 'o' },
358 i = mdwopt(argc, argv, "abf:o:qvC", opt, 0, 0, 0);
361 case 'a': ef = "pem"; break;
362 case 'b': f |= f_buffer; break;
363 case 'v': verb++; break;
364 case 'q': if (verb) verb--; break;
365 case 'C': f |= f_nocheck; break;
366 case 'f': ef = optarg; break;
367 case 'o': of = optarg; break;
368 default: f |= f_bogus; break;
371 if (argc - optind > 1 || (f & f_bogus))
372 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
374 if ((eo = getenc(ef)) == 0)
375 die(EXIT_FAILURE, "encoding `%s' not found", ef);
379 else if (strcmp(argv[optind], "-") == 0) {
382 } else if ((fp = fopen(argv[optind], eo->rmode)) == 0) {
383 die(EXIT_FAILURE, "couldn't open file `%s': %s",
384 argv[optind], strerror(errno));
388 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
389 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
391 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
393 /* --- Read the header chunk --- */
395 chunk_read(e, &d, &b);
396 if (buf_getu32(&b, &id)) {
397 if (verb) printf("FAIL malformed header: missing keyid\n");
400 if ((k = key_byid(&kf, id)) == 0) {
401 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
405 if (buf_getu32(&b, &id)) {
406 if (verb) printf("FAIL malformed header: missing signature keyid\n");
409 if ((sk = key_byid(&kf, id)) == 0) {
410 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
415 if (verb) printf("FAIL malformed header: junk at end\n");
419 /* --- Find the key --- */
421 km = getkem(k, "cckem", 1);
423 /* --- Read the KEM chunk --- */
425 chunk_read(e, &d, &b);
426 if (setupkem(km, &d, &cx, &c, &m)) {
427 if (verb) printf("FAIL failed to decapsulate key\n");
431 /* --- Verify the signature, if there is one --- */
434 s = getsig(sk, "ccsig", 0);
437 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0)
438 printf("WARN verification key %s fails check: %s\n", d.buf, err);
440 dstr_ensure(&d, 1024);
441 GC_ENCRYPT(cx, 0, d.buf, 1024);
442 GH_HASH(s->h, d.buf, 1024);
443 chunk_read(e, &d, &b);
444 if (s->ops->doit(s, &d)) {
445 if (verb) printf("FAIL signature verification failed\n");
451 printf("INFO good-signature %s\n", d.buf);
455 printf("INFO no-signature\n");
457 /* --- Now decrypt the main body --- */
459 if (!of || strcmp(of, "-") == 0) {
463 if (!(f & f_buffer)) {
464 if ((ofp = fopen(of, "wb")) == 0) {
465 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
466 ofp, strerror(errno));
469 } else if ((rfp = tmpfile()) == 0)
470 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
473 dstr_ensure(&d, GC_CLASS(c)->blksz);
476 if (GC_CLASS(c)->blksz) {
477 GC_ENCRYPT(cx, 0, d.buf, GC_CLASS(c)->blksz);
483 chunk_read(e, &d, &b);
484 if ((tag = buf_get(&b, GM_CLASS(m)->hashsz)) == 0) {
485 if (verb) printf("FAIL bad ciphertext chunk: no tag\n");
488 GH_HASH(h, BCUR(&b), BLEFT(&b));
489 if (memcmp(tag, GH_DONE(h, 0), GM_CLASS(m)->hashsz) != 0) {
491 printf("FAIL bad ciphertext chunk: authentication failure\n");
497 GC_DECRYPT(c, BCUR(&b), BCUR(&b), BLEFT(&b));
498 if (fwrite(BCUR(&b), 1, BLEFT(&b), rfp) != BLEFT(&b)) {
499 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
504 if (fflush(rfp) || ferror(rfp)) {
505 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
509 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
510 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
511 of, strerror(errno));
515 dstr_ensure(&d, 65536);
516 if (verb && ofp == stdout) printf("DATA\n");
518 n = fread(d.buf, 1, d.sz, rfp);
520 if (fwrite(d.buf, 1, n, ofp) < n)
521 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
523 if (ferror(rfp) || fclose(rfp))
524 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
526 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
527 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
530 if (verb && ofp != stdout)
531 printf("OK decrypted successfully\n");
537 if (fp != stdin) fclose(fp);
548 /*----- Main code ---------------------------------------------------------*/
552 listtab[i].name, listtab[i].name) \
553 LI("Key-encapsulation mechanisms", kem, \
554 kemtab[i].name, kemtab[i].name) \
555 LI("Signature schemes", sig, \
556 sigtab[i].name, sigtab[i].name) \
557 LI("Encodings", enc, \
558 enctab[i].name, enctab[i].name) \
559 LI("Symmetric encryption algorithms", cipher, \
560 gciphertab[i], gciphertab[i]->name) \
561 LI("Hash functions", hash, \
562 ghashtab[i], ghashtab[i]->name) \
563 LI("Message authentication codes", mac, \
564 gmactab[i], gmactab[i]->name)
566 MAKELISTTAB(listtab, LISTS)
568 int cmd_show(int argc, char *argv[])
570 return (displaylists(listtab, argv + 1));
573 static int cmd_help(int, char **);
575 static cmd cmdtab[] = {
576 { "help", cmd_help, "help [COMMAND...]" },
577 { "show", cmd_show, "show [ITEM...]" },
580 { "encrypt", encrypt,
581 "encrypt [-aC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
582 [-o OUTPUT] [FILE]", "\
585 -a, --armour Same as `-f pem'.\n\
586 -f, --format=FORMAT Encode as FORMAT.\n\
587 -k, --key=TAG Use public encryption key named by TAG.\n\
588 -s, --sign-key=TAG Use private signature key named by TAG.\n\
589 -o, --output=FILE Write output to FILE.\n\
590 -C, --nocheck Don't check the public key.\n\
592 { "decrypt", decrypt,
593 "decrypt [-abqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
596 -a, --armour Same as `-f pem'.\n\
597 -b, --buffer Buffer output until we're sure we have it all.\n\
598 -f, --format=FORMAT Decode as FORMAT.\n\
599 -o, --output=FILE Write output to FILE.\n\
600 -q, --quiet Produce fewer messages.\n\
601 -v, --verbose Produce more verbose messages.\n\
602 -C, --nocheck Don't check the private key.\n\
603 " }, /* ' emacs is confused */
607 static int cmd_help(int argc, char **argv)
609 sc_help(cmdtab, stdout, argv + 1);
613 void version(FILE *fp)
615 pquis(fp, "$, Catacomb version " VERSION "\n");
618 static void usage(FILE *fp)
620 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
623 void help_global(FILE *fp)
627 Encrypt and decrypt files.\n\
629 Global command-line options:\n\
631 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
632 -v, --version Show program version number.\n\
633 -u, --usage Show a terse usage message.\n\
635 -k, --keyring=FILE Read keys from FILE.\n",
641 * Arguments: @int argc@ = number of command line arguments
642 * @char *argv[]@ = vector of command line arguments
644 * Returns: Zero if successful, nonzero otherwise.
646 * Use: Encrypts or decrypts files.
649 int main(int argc, char *argv[])
655 /* --- Initialize the library --- */
659 rand_noisesrc(RAND_GLOBAL, &noise_source);
660 rand_seed(RAND_GLOBAL, 160);
662 /* --- Parse options --- */
665 static struct option opts[] = {
666 { "help", 0, 0, 'h' },
667 { "version", 0, 0, 'v' },
668 { "usage", 0, 0, 'u' },
669 { "keyring", OPTF_ARGREQ, 0, 'k' },
672 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
677 sc_help(cmdtab, stdout, argv + optind);
699 if (f & f_bogus || argc < 1) {
704 /* --- Dispatch to the correct subcommand handler --- */
706 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
711 /*----- That's all, folks -------------------------------------------------*/