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";
155 #define f_progress 4u
158 static const struct option opt[] = {
159 { "key", OPTF_ARGREQ, 0, 'k' },
160 { "sign-key", OPTF_ARGREQ, 0, 's' },
161 { "armour", 0, 0, 'a' },
162 { "armor", 0, 0, 'a' },
163 { "format", OPTF_ARGREQ, 0, 'f' },
164 { "output", OPTF_ARGREQ, 0, 'o' },
165 { "progress", 0, 0, 'p' },
166 { "nocheck", 0, 0, 'C' },
169 i = mdwopt(argc, argv, "k:s:af:o:pC", 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 'p': f |= f_progress; break;
178 case 'C': f |= f_nocheck; break;
179 default: f |= f_bogus; break;
182 if (argc - optind > 1 || (f & f_bogus))
183 die(EXIT_FAILURE, "Usage: encrypt [-OPTIONS] [FILE]");
185 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
186 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
187 if ((k = key_bytag(&kf, kn)) == 0)
188 die(EXIT_FAILURE, "key `%s' not found", kn);
189 if (skn && (sk = key_bytag(&kf, skn)) == 0)
190 die(EXIT_FAILURE, "key `%s' not found", skn);
192 if ((eo = getenc(ef)) == 0)
193 die(EXIT_FAILURE, "encoding `%s' not found", ef);
195 fn = optind < argc ? argv[optind++] : "-";
196 if (strcmp(fn, "-") == 0)
198 else if ((fp = fopen(fn, "rb")) == 0) {
199 die(EXIT_FAILURE, "couldn't open file `%s': %s",
200 fn, strerror(errno));
203 if (!of || strcmp(of, "-") == 0)
205 else if ((ofp = fopen(of, eo->wmode)) == 0) {
206 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
207 of, strerror(errno));
212 e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE");
213 km = getkem(k, "cckem", 0, &bc);
214 if (!(f & f_nocheck) && (err = km->ops->check(km)) != 0)
215 moan("key %s fails check: %s", d.buf, err);
219 s = getsig(sk, "ccsig", 1);
220 if ((err = s->ops->check(s)) != 0)
221 moan("key %s fails check: %s", d.buf, err);
224 /* --- Build the header chunk --- */
227 dstr_ensure(&d, 256);
228 buf_init(&b, d.buf, 256);
229 buf_putu32(&b, k->id);
230 if (sk) buf_putu32(&b, sk->id);
232 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
235 /* --- Build the KEM chunk --- */
238 if (setupkem(km, &d, bc)) die(EXIT_FAILURE, "failed to encapsulate key");
239 buf_init(&b, d.buf, d.len);
241 if (s) GH_HASHBUF16(s->h, BBASE(&b), BLEN(&b));
244 /* --- Write the signature chunk --- */
247 GC_ENCRYPT(km->cx, 0, bb, 1024);
248 GH_HASH(s->h, bb, 1024);
250 if ((en = s->ops->doit(s, &d)) != 0)
251 die(EXIT_FAILURE, "error creating signature: %s", key_strerror(en));
252 buf_init(&b, d.buf, d.len);
257 /* --- Now do the main crypto --- */
259 if (f & f_progress) {
260 if (fprogress_init(&ff, fn, fp)) {
261 die(EXIT_FAILURE, "failed to initialize progress display: %s",
266 n = bc->ops->overhead(bc);
267 dstr_ensure(&d, sizeof(bb) + n);
271 n = fread(bb, 1, chsz, fp);
272 if (f & f_progress) fprogress_update(&ff, n);
273 buf_init(&b, d.buf, d.sz);
274 if ((err = bc->ops->doit(bc, seq, &b, bb, n)) != 0) {
275 if (f & f_progress) fprogress_done(&ff);
276 die(EXIT_FAILURE, "failed to encrypt packet: %s\n", err);
282 /* --- All done --- */
284 if (f & f_progress) fprogress_done(&ff);
286 bc->ops->destroy(bc);
290 if (fp != stdin) fclose(fp);
301 /*---- Decryption ---------------------------------------------------------*/
303 static int decrypt(int argc, char *argv[])
305 const char *fn, *of = 0;
306 FILE *ofp = 0, *rfp = 0;
308 const char *ef = "binary";
332 #define f_progress 8u
335 static const struct option opt[] = {
336 { "armour", 0, 0, 'a' },
337 { "armor", 0, 0, 'a' },
338 { "buffer", 0, 0, 'b' },
339 { "verbose", 0, 0, 'v' },
340 { "quiet", 0, 0, 'q' },
341 { "nocheck", 0, 0, 'C' },
342 { "format", OPTF_ARGREQ, 0, 'f' },
343 { "output", OPTF_ARGREQ, 0, 'o' },
344 { "progress", 0, 0, 'p' },
347 i = mdwopt(argc, argv, "abf:o:pqvC", opt, 0, 0, 0);
350 case 'a': ef = "pem"; break;
351 case 'b': f |= f_buffer; break;
352 case 'v': verb++; break;
353 case 'q': if (verb) verb--; break;
354 case 'C': f |= f_nocheck; break;
355 case 'f': ef = optarg; break;
356 case 'o': of = optarg; break;
357 case 'p': f |= f_progress; break;
358 default: f |= f_bogus; break;
361 if (argc - optind > 1 || (f & f_bogus))
362 die(EXIT_FAILURE, "Usage: decrypt [-OPTIONS] [FILE]");
364 if ((eo = getenc(ef)) == 0)
365 die(EXIT_FAILURE, "encoding `%s' not found", ef);
367 fn = optind < argc ? argv[optind++] : "-";
368 if (strcmp(fn, "-") == 0)
370 else if ((fp = fopen(fn, eo->rmode)) == 0) {
371 die(EXIT_FAILURE, "couldn't open file `%s': %s",
372 fn, strerror(errno));
375 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
376 die(EXIT_FAILURE, "can't open keyring `%s'", keyring);
378 e = initdec(eo, fp, checkbdry, "CATCRYPT ENCRYPTED MESSAGE");
380 if (f & f_progress) {
381 if (fprogress_init(&ff, fn, fp)) {
382 die(EXIT_FAILURE, "failed to initialize progress display: %s",
387 /* --- Read the header chunk --- */
389 chunk_read(e, &d, &b);
391 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
392 if (buf_getu32(&b, &id)) {
393 if (f & f_progress) fprogress_done(&ff);
394 if (verb) printf("FAIL malformed header: missing keyid\n");
397 if ((k = key_byid(&kf, id)) == 0) {
398 if (f & f_progress) fprogress_done(&ff);
399 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
403 if (buf_getu32(&b, &id)) {
404 if (f & f_progress) fprogress_done(&ff);
405 if (verb) printf("FAIL malformed header: missing signature keyid\n");
408 if ((sk = key_byid(&kf, id)) == 0) {
409 if (f & f_progress) fprogress_done(&ff);
410 if (verb) printf("FAIL key id %08lx not found\n", (unsigned long)id);
415 if (f & f_progress) fprogress_done(&ff);
416 if (verb) printf("FAIL malformed header: junk at end\n");
420 s = getsig(sk, "ccsig", 0);
421 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0) {
424 printf("WARN verification key %s fails check: %s\n", d.buf, err);
426 GH_HASHBUF16(s->h, BBASE(&b), BSZ(&b));
429 /* --- Find the key --- */
431 km = getkem(k, "cckem", 1, &bc);
433 /* --- Read the KEM chunk --- */
435 chunk_read(e, &d, &b);
437 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
438 if (setupkem(km, &d, bc)) {
439 if (f & f_progress) fprogress_done(&ff);
440 if (verb) printf("FAIL failed to decapsulate key\n");
443 if (s) GH_HASHBUF16(s->h, d.buf, d.len);
445 /* --- Verify the signature, if there is one --- */
449 dstr_ensure(&d, 1024);
450 GC_ENCRYPT(km->cx, 0, d.buf, 1024);
451 GH_HASH(s->h, d.buf, 1024);
452 chunk_read(e, &d, &b);
454 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
455 if (s->ops->doit(s, &d)) {
456 if (f & f_progress) fprogress_done(&ff);
457 if (verb) printf("FAIL signature verification failed\n");
463 if (f & f_progress) fprogress_clear(&ff);
464 printf("INFO good-signature %s\n", d.buf);
468 if (f & f_progress) fprogress_clear(&ff);
469 printf("INFO no-signature\n");
472 /* --- Now decrypt the main body --- */
474 if (!of || strcmp(of, "-") == 0) {
478 if (!(f & f_buffer)) {
479 if ((ofp = fopen(of, "wb")) == 0) {
480 if (f & f_progress) fprogress_done(&ff);
481 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
482 of, strerror(errno));
485 } else if ((rfp = tmpfile()) == 0) {
486 if (f & f_progress) fprogress_done(&ff);
487 die(EXIT_FAILURE, "couldn't create temporary file: %s", strerror(errno));
491 dstr_ensure(&d, bc->ops->overhead(bc));
494 chunk_read(e, &d, &b);
496 fprogress_update(&ff, BLEFT(&b)*e->ops->ncook/e->ops->nraw);
497 buf_init(&b, bb, sizeof(bb));
498 if ((err = bc->ops->doit(bc, seq, &b, d.buf, d.len)) != 0) {
499 if (f & f_progress) fprogress_done(&ff);
500 if (verb) printf("FAIL bad ciphertext chunk: %s\n", err);
504 if (!BLEN(&b)) break;
505 if (fwrite(BBASE(&b), 1, BLEN(&b), rfp) != BLEN(&b)) {
506 if (f & f_progress) fprogress_done(&ff);
507 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
512 if (f & f_progress) fprogress_done(&ff);
513 if (fflush(rfp) || ferror(rfp)) {
514 if (verb) printf("FAIL error writing output: %s\n", strerror(errno));
518 if (!ofp && (ofp = fopen(of, "wb")) == 0) {
519 die(EXIT_FAILURE, "couldn't open file `%s' for output: %s",
520 of, strerror(errno));
523 if (f & f_progress) fprogress_init(&ff, "copying buffer", rfp);
525 dstr_ensure(&d, 65536);
526 if (verb && ofp == stdout) printf("DATA\n");
528 n = fread(d.buf, 1, d.sz, rfp);
530 if (f & f_progress) fprogress_update(&ff, n);
531 if (fwrite(d.buf, 1, n, ofp) < n) {
532 if (f & f_progress) fprogress_done(&ff);
533 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
536 if (f & f_progress) fprogress_done(&ff);
537 if (ferror(rfp) || fclose(rfp))
538 die(EXIT_FAILURE, "error unbuffering output: %s", strerror(errno));
542 if (verb && ofp != stdout)
543 printf("OK decrypted successfully\n");
544 if (ofp && (fflush(ofp) || ferror(ofp) || fclose(ofp)))
545 die(EXIT_FAILURE, "error writing output: %s", strerror(errno));
546 bc->ops->destroy(bc);
549 if (fp != stdin) fclose(fp);
560 /*----- Main code ---------------------------------------------------------*/
564 listtab[i].name, listtab[i].name) \
565 LI("Key-encapsulation mechanisms", kem, \
566 kemtab[i].name, kemtab[i].name) \
567 LI("Bulk crypto transforms", bulk, \
568 bulktab[i].name, bulktab[i].name) \
569 LI("Signature schemes", sig, \
570 sigtab[i].name, sigtab[i].name) \
571 LI("Encodings", enc, \
572 enctab[i].name, enctab[i].name) \
573 LI("Symmetric encryption algorithms", cipher, \
574 gciphertab[i], gciphertab[i]->name) \
575 LI("Hash functions", hash, \
576 ghashtab[i], ghashtab[i]->name) \
577 LI("Message authentication codes", mac, \
578 gmactab[i], gmactab[i]->name)
580 MAKELISTTAB(listtab, LISTS)
582 int cmd_show(int argc, char *argv[])
584 return (displaylists(listtab, argv + 1));
587 static int cmd_help(int, char **);
589 static cmd cmdtab[] = {
590 { "help", cmd_help, "help [COMMAND...]" },
591 { "show", cmd_show, "show [ITEM...]" },
594 { "encrypt", encrypt,
595 "encrypt [-apC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
596 [-o OUTPUT] [FILE]", "\
599 -a, --armour Same as `-f pem'.\n\
600 -f, --format=FORMAT Encode as FORMAT.\n\
601 -k, --key=TAG Use public encryption key named by TAG.\n\
602 -s, --sign-key=TAG Use private signature key named by TAG.\n\
603 -o, --output=FILE Write output to FILE.\n\
604 -p, --progress Show progress on large files.\n\
605 -C, --nocheck Don't check the public key.\n\
607 { "decrypt", decrypt,
608 "decrypt [-abpqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
611 -a, --armour Same as `-f pem'.\n\
612 -b, --buffer Buffer output until we're sure we have it all.\n\
613 -f, --format=FORMAT Decode as FORMAT.\n\
614 -o, --output=FILE Write output to FILE.\n\
615 -p, --progress Show progress on large files.\n\
616 -q, --quiet Produce fewer messages.\n\
617 -v, --verbose Produce more verbose messages.\n\
618 -C, --nocheck Don't check the private key.\n\
623 static int cmd_help(int argc, char **argv)
625 sc_help(cmdtab, stdout, argv + 1);
629 void version(FILE *fp)
631 pquis(fp, "$, Catacomb version " VERSION "\n");
634 static void usage(FILE *fp)
636 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
639 void help_global(FILE *fp)
643 Encrypt and decrypt files.\n\
645 Global command-line options:\n\
647 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
648 -v, --version Show program version number.\n\
649 -u, --usage Show a terse usage message.\n\
651 -k, --keyring=FILE Read keys from FILE.\n",
657 * Arguments: @int argc@ = number of command line arguments
658 * @char *argv[]@ = vector of command line arguments
660 * Returns: Zero if successful, nonzero otherwise.
662 * Use: Encrypts or decrypts files.
665 int main(int argc, char *argv[])
671 /* --- Initialize the library --- */
675 rand_noisesrc(RAND_GLOBAL, &noise_source);
676 rand_seed(RAND_GLOBAL, 160);
678 /* --- Parse options --- */
681 static struct option opts[] = {
682 { "help", 0, 0, 'h' },
683 { "version", 0, 0, 'v' },
684 { "usage", 0, 0, 'u' },
685 { "keyring", OPTF_ARGREQ, 0, 'k' },
688 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
693 sc_help(cmdtab, stdout, argv + optind);
715 if (f & f_bogus || argc < 1) {
720 /* --- Dispatch to the correct subcommand handler --- */
722 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
727 /*----- That's all, folks -------------------------------------------------*/