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 /* --- @keyreport@ --- *
60 * Arguments: @const char *file@ = filename containing the error
61 * @int line@ = line number in file
62 * @const char *err@ = error text message
63 * @void *p@ = unimportant pointer
67 * Use: Reports errors during the opening of a key file.
70 static void keyreport(const char *file
, int line
, const char *err
, void *p
)
72 moan("error in keyring `%s' at line `%s': %s", file
, line
, err
);
75 /*----- Static variables --------------------------------------------------*/
77 static const char *keyring
= "keyring";
79 /*----- Data format -------------------------------------------------------*/
83 * The encrypted message is divided into chunks, each preceded by a two-octet
84 * length. The chunks don't need to be large -- the idea is that we can
85 * stream the chunks in and out.
87 * The first chunk is a header. It contains the decryption key-id, and maybe
88 * the verification key-id if the message is signed.
90 * Next comes the key-encapsulation chunk. This is decrypted in some
91 * KEM-specific way to yield a secret hash. The hash is expanded using an
92 * MGF (or similar) to make a symmetric encryption and MAC key.
94 * If the message is signed, there comes a signature chunk. The signature is
95 * on the further output of the MGF. This means that the recipient can
96 * modify the message and still have a valid signature, so it's not useful
97 * for proving things to other people; but it also means that the recipient
98 * knows that the message is from someone who knows the hash, which limits
99 * the possiblities to (a) whoever encrypted the message (good!) and (b)
100 * whoever knows the recipient's private key.
102 * Then come message chunks. Each one begins with a MAC over an implicit
103 * sequence number and the ciphertext. The final chunk's ciphertext is
104 * empty; no other chunk is empty. Thus can the correct end-of-file be
108 /*----- Chunk I/O ---------------------------------------------------------*/
110 static void chunk_write(enc
*e
, buf
*b
)
116 if (e
->ops
->write(e
, l
, 2) ||
117 e
->ops
->write(e
, BBASE(b
), BLEN(b
)))
118 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
121 static void chunk_read(enc
*e
, dstr
*d
, buf
*b
)
128 if (e
->ops
->read(e
, l
, 2) != 2)
132 if (e
->ops
->read(e
, d
->buf
, n
) != n
)
135 buf_init(b
, d
->buf
, d
->len
);
139 if (!errno
) die(EXIT_FAILURE
, "unexpected end-of-file on input");
140 else die(EXIT_FAILURE
, "error reading input: %s", strerror(errno
));
143 /*----- Encryption --------------------------------------------------------*/
145 static int encrypt(int argc
, char *argv
[])
147 const char *of
= 0, *kn
= "ccrypt", *skn
= 0;
150 const char *ef
= "binary";
175 static const struct option opt
[] = {
176 { "key", OPTF_ARGREQ
, 0, 'k' },
177 { "sign-key", OPTF_ARGREQ
, 0, 's' },
178 { "armour", 0, 0, 'a' },
179 { "armor", 0, 0, 'a' },
180 { "format", OPTF_ARGREQ
, 0, 'f' },
181 { "output", OPTF_ARGREQ
, 0, 'o' },
184 i
= mdwopt(argc
, argv
, "k:s:af:o:", opt
, 0, 0, 0);
187 case 'k': kn
= optarg
; break;
188 case 's': skn
= optarg
; break;
189 case 'a': ef
= "pem"; break;
190 case 'f': ef
= optarg
; break;
191 case 'o': of
= optarg
; break;
192 default: f
|= f_bogus
; break;
195 if (argc
- optind
> 1 || (f
& f_bogus
))
196 die(EXIT_FAILURE
, "Usage: encrypt [-OPTIONS] [FILE]");
198 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
199 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
200 if ((k
= key_bytag(&kf
, kn
)) == 0)
201 die(EXIT_FAILURE
, "key `%s' not found", kn
);
202 if (skn
&& (sk
= key_bytag(&kf
, skn
)) == 0)
203 die(EXIT_FAILURE
, "key `%s' not found", skn
);
205 if ((eo
= getenc(ef
)) == 0)
206 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
210 else if (strcmp(argv
[optind
], "-") == 0) {
213 } else if ((fp
= fopen(argv
[optind
], "rb")) == 0) {
214 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
215 argv
[optind
], strerror(errno
));
219 if (!of
|| strcmp(of
, "-") == 0)
221 else if ((ofp
= fopen(of
, eo
->wmode
)) == 0) {
222 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
223 ofp
, strerror(errno
));
228 e
= initenc(eo
, ofp
, "CATCRYPT ENCRYPTED MESSAGE");
229 km
= getkem(k
, "cckem", 0);
230 if ((err
= km
->ops
->check(km
)) != 0)
231 moan("key %s fails check: %s", d
.buf
, err
);
235 s
= getsig(sk
, "ccsig", 1);
236 if ((err
= s
->ops
->check(s
)) != 0)
237 moan("key %s fails check: %s", d
.buf
, err
);
240 /* --- Build the header chunk --- */
243 dstr_ensure(&d
, 256);
244 buf_init(&b
, d
.buf
, 256);
245 buf_putu32(&b
, k
->id
);
246 if (sk
) buf_putu32(&b
, sk
->id
);
250 /* --- Build the KEM chunk --- */
253 if (setupkem(km
, &d
, &cx
, &c
, &m
))
254 die(EXIT_FAILURE
, "failed to encapsulate key");
255 buf_init(&b
, d
.buf
, d
.len
);
259 /* --- Write the signature chunk --- */
262 GC_ENCRYPT(cx
, 0, bb
, 1024);
263 GH_HASH(s
->h
, bb
, 1024);
265 if ((en
= s
->ops
->doit(s
, &d
)) != 0)
266 die(EXIT_FAILURE
, "error creating signature: %s", key_strerror(en
));
267 buf_init(&b
, d
.buf
, d
.len
);
272 /* --- Now do the main crypto --- */
274 assert(GC_CLASS(c
)->blksz
<= sizeof(bb
));
275 dstr_ensure(&d
, sizeof(bb
) + GM_CLASS(m
)->hashsz
);
281 if (GC_CLASS(c
)->blksz
) {
282 GC_ENCRYPT(cx
, 0, bb
, GC_CLASS(c
)->blksz
);
285 n
= fread(bb
, 1, sizeof(bb
), fp
);
287 buf_init(&b
, d
.buf
, d
.sz
);
288 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
290 assert(tag
); assert(ct
);
291 GC_ENCRYPT(c
, bb
, ct
, n
);
298 /* --- Final terminator packet --- */
300 buf_init(&b
, d
.buf
, d
.sz
);
301 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
307 /* --- All done --- */
316 if (fp
!= stdin
) fclose(fp
);
325 /*---- Decryption ---------------------------------------------------------*/
327 static int decrypt(int argc
, char *argv
[])
330 FILE *ofp
= 0, *rfp
= 0;
332 const char *ef
= "binary";
359 static const struct option opt
[] = {
360 { "armour", 0, 0, 'a' },
361 { "armor", 0, 0, 'a' },
362 { "buffer", 0, 0, 'b' },
363 { "verbose", 0, 0, 'v' },
364 { "quiet", 0, 0, 'q' },
365 { "format", OPTF_ARGREQ
, 0, 'f' },
366 { "output", OPTF_ARGREQ
, 0, 'o' },
369 i
= mdwopt(argc
, argv
, "abf:o:qv", opt
, 0, 0, 0);
372 case 'a': ef
= "pem"; break;
373 case 'b': f
|= f_buffer
; break;
374 case 'v': verb
++; break;
375 case 'q': if (verb
) verb
--; break;
376 case 'f': ef
= optarg
; break;
377 case 'o': of
= optarg
; break;
378 default: f
|= f_bogus
; break;
381 if (argc
- optind
> 1 || (f
& f_bogus
))
382 die(EXIT_FAILURE
, "Usage: decrypt [-OPTIONS] [FILE]");
384 if ((eo
= getenc(ef
)) == 0)
385 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
389 else if (strcmp(argv
[optind
], "-") == 0) {
392 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
393 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
394 argv
[optind
], strerror(errno
));
398 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
399 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
401 e
= initdec(eo
, fp
, checkbdry
, "CATCRYPT ENCRYPTED MESSAGE");
403 /* --- Read the header chunk --- */
405 chunk_read(e
, &d
, &b
);
406 if (buf_getu32(&b
, &id
)) {
407 if (verb
) printf("FAIL malformed header: missing keyid\n");
410 if ((k
= key_byid(&kf
, id
)) == 0) {
411 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
415 if (buf_getu32(&b
, &id
)) {
416 if (verb
) printf("FAIL malformed header: missing signature keyid\n");
419 if ((sk
= key_byid(&kf
, id
)) == 0) {
420 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
425 if (verb
) printf("FAIL malformed header: junk at end\n");
429 /* --- Find the key --- */
431 km
= getkem(k
, "cckem", 1);
433 /* --- Read the KEM chunk --- */
435 chunk_read(e
, &d
, &b
);
436 if (setupkem(km
, &d
, &cx
, &c
, &m
)) {
437 if (verb
) printf("FAIL failed to decapsulate key\n");
441 /* --- Verify the signature, if there is one --- */
444 s
= getsig(sk
, "ccsig", 0);
447 if (verb
&& (err
= s
->ops
->check(s
)) != 0)
448 printf("WARN verification key %s fails check: %s\n", d
.buf
, err
);
450 dstr_ensure(&d
, 1024);
451 GC_ENCRYPT(cx
, 0, d
.buf
, 1024);
452 GH_HASH(s
->h
, d
.buf
, 1024);
453 chunk_read(e
, &d
, &b
);
454 if (s
->ops
->doit(s
, &d
)) {
455 if (verb
) printf("FAIL signature verification failed\n");
461 printf("INFO good-signature %s\n", d
.buf
);
465 printf("INFO no-signature\n");
467 /* --- Now decrypt the main body --- */
469 if (!of
|| strcmp(of
, "-") == 0) {
473 if (!(f
& f_buffer
)) {
474 if ((ofp
= fopen(of
, "wb")) == 0) {
475 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
476 ofp
, strerror(errno
));
479 } else if ((rfp
= tmpfile()) == 0)
480 die(EXIT_FAILURE
, "couldn't create temporary file: %s", strerror(errno
));
483 dstr_ensure(&d
, GC_CLASS(c
)->blksz
);
486 if (GC_CLASS(c
)->blksz
) {
487 GC_ENCRYPT(cx
, 0, d
.buf
, GC_CLASS(c
)->blksz
);
493 chunk_read(e
, &d
, &b
);
494 if ((tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
)) == 0) {
495 if (verb
) printf("FAIL bad ciphertext chunk: no tag\n");
498 GH_HASH(h
, BCUR(&b
), BLEFT(&b
));
499 if (memcmp(tag
, GH_DONE(h
, 0), GM_CLASS(m
)->hashsz
) != 0) {
501 printf("FAIL bad ciphertext chunk: authentication failure\n");
507 GC_DECRYPT(c
, BCUR(&b
), BCUR(&b
), BLEFT(&b
));
508 if (fwrite(BCUR(&b
), 1, BLEFT(&b
), rfp
) != BLEFT(&b
)) {
509 if (verb
) printf("FAIL error writing output: %s\n", strerror(errno
));
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
));
525 dstr_ensure(&d
, 65536);
526 if (verb
&& ofp
== stdout
) printf("DATA\n");
528 n
= fread(d
.buf
, 1, d
.sz
, rfp
);
530 if (fwrite(d
.buf
, 1, n
, ofp
) < n
)
531 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
533 if (ferror(rfp
) || fclose(rfp
))
534 die(EXIT_FAILURE
, "error unbuffering output: %s", strerror(errno
));
536 if (ofp
&& (fflush(ofp
) || ferror(ofp
) || fclose(ofp
)))
537 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
540 if (verb
&& ofp
!= stdout
)
541 printf("OK decrypted successfully\n");
547 if (fp
!= stdin
) fclose(fp
);
557 /*----- Main code ---------------------------------------------------------*/
561 listtab[i].name, listtab[i].name) \
562 LI("Key-encapsulation mechanisms", kem, \
563 kemtab[i].name, kemtab[i].name) \
564 LI("Signature schemes", sig, \
565 sigtab[i].name, sigtab[i].name) \
566 LI("Encodings", enc, \
567 enctab[i].name, enctab[i].name) \
568 LI("Symmetric encryption algorithms", cipher, \
569 gciphertab[i], gciphertab[i]->name) \
570 LI("Hash functions", hash, \
571 ghashtab[i], ghashtab[i]->name) \
572 LI("Message authentication codes", mac, \
573 gmactab[i], gmactab[i]->name)
575 MAKELISTTAB(listtab
, LISTS
)
577 int cmd_show(int argc
, char *argv
[])
579 return (displaylists(listtab
, argv
+ 1));
582 static int cmd_help(int, char **);
584 static cmd cmdtab
[] = {
585 { "help", cmd_help
, "help [COMMAND...]" },
586 { "show", cmd_show
, "show [ITEM...]" },
589 { "encrypt", encrypt
,
590 "encrypt [-a] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
591 [-o OUTPUT] [FILE]", "\
594 -a, --armour Same as `-f pem'.\n\
595 -f, --format=FORMAT Encode as FORMAT.\n\
596 -k, --key=TAG Use public encryption key named by TAG.\n\
597 -s, --sign-key=TAG Use private signature key named by TAG.\n\
598 -o, --output=FILE Write output to FILE.\n\
600 { "decrypt", decrypt
,
601 "decrypt [-abqv] [-f FORMAT] [-o OUTPUT] [FILE]", "\
604 -a, --armour Same as `-f pem'.\n\
605 -b, --buffer Buffer output until we're sure we have it all.\n\
606 -f, --format=FORMAT Decode as FORMAT.\n\
607 -o, --output=FILE Write output to FILE.\n\
608 -q, --quiet Produce fewer messages.\n\
609 -v, --verbose Produce more verbose messages.\n\
610 " }, /* ' emacs is confused */
614 static int cmd_help(int argc
, char **argv
)
616 sc_help(cmdtab
, stdout
, argv
+ 1);
620 void version(FILE *fp
)
622 pquis(fp
, "$, Catacomb version " VERSION
"\n");
625 static void usage(FILE *fp
)
627 pquis(fp
, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
630 void help_global(FILE *fp
)
634 Encrypt and decrypt files.\n\
636 Global command-line options:\n\
638 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
639 -v, --version Show program version number.\n\
640 -u, --usage Show a terse usage message.\n\
642 -k, --keyring=FILE Read keys from FILE.\n",
648 * Arguments: @int argc@ = number of command line arguments
649 * @char *argv[]@ = vector of command line arguments
651 * Returns: Zero if successful, nonzero otherwise.
653 * Use: Encrypts or decrypts files.
656 int main(int argc
, char *argv
[])
662 /* --- Initialize the library --- */
666 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
667 rand_seed(RAND_GLOBAL
, 160);
669 /* --- Parse options --- */
672 static struct option opts
[] = {
673 { "help", 0, 0, 'h' },
674 { "version", 0, 0, 'v' },
675 { "usage", 0, 0, 'u' },
676 { "keyring", OPTF_ARGREQ
, 0, 'k' },
679 int i
= mdwopt(argc
, argv
, "+hvu k:", opts
, 0, 0, 0);
684 sc_help(cmdtab
, stdout
, argv
+ optind
);
706 if (f
& f_bogus
|| argc
< 1) {
711 /* --- Dispatch to the correct subcommand handler --- */
713 return (findcmd(cmdtab
, argv
[0])->cmd(argc
, argv
));
718 /*----- That's all, folks -------------------------------------------------*/