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 /*----- Static variables --------------------------------------------------*/
58 static const char *keyring
= "keyring";
60 /*----- Data format -------------------------------------------------------*/
64 * The encrypted message is divided into chunks, each preceded by a two-octet
65 * length. The chunks don't need to be large -- the idea is that we can
66 * stream the chunks in and out.
68 * The first chunk is a header. It contains the decryption key-id, and maybe
69 * the verification key-id if the message is signed.
71 * Next comes the key-encapsulation chunk. This is decrypted in some
72 * KEM-specific way to yield a secret hash. The hash is expanded using an
73 * MGF (or similar) to make a symmetric encryption and MAC key.
75 * If the message is signed, there comes a signature chunk. The signature is
76 * on the header and key-encapsulation chunks, and further output of the MGF.
77 * This means that the recipient can modify the message and still have a
78 * valid signature, so it's not useful for proving things to other people;
79 * but it also means that the recipient knows that the message is from
80 * someone who knows the hash, which limits the possiblities to (a) whoever
81 * encrypted the message (good!) and (b) whoever knows the recipient's
84 * Then come message chunks. Each one begins with a MAC over an implicit
85 * sequence number and the ciphertext. The final chunk's ciphertext is
86 * empty; no other chunk is empty. Thus can the correct end-of-file be
90 /*----- Chunk I/O ---------------------------------------------------------*/
92 static void chunk_write(enc
*e
, buf
*b
)
98 if (e
->ops
->write(e
, l
, 2) ||
99 e
->ops
->write(e
, BBASE(b
), BLEN(b
)))
100 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
103 static void chunk_read(enc
*e
, dstr
*d
, buf
*b
)
110 if (e
->ops
->read(e
, l
, 2) != 2)
114 if (e
->ops
->read(e
, d
->buf
, n
) != n
)
117 buf_init(b
, d
->buf
, d
->len
);
121 if (!errno
) die(EXIT_FAILURE
, "unexpected end-of-file on input");
122 else die(EXIT_FAILURE
, "error reading input: %s", strerror(errno
));
125 /*----- Encryption --------------------------------------------------------*/
127 static int encrypt(int argc
, char *argv
[])
129 const char *of
= 0, *kn
= "ccrypt", *skn
= 0;
132 const char *ef
= "binary";
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 { "nocheck", 0, 0, 'C' },
168 i
= mdwopt(argc
, argv
, "k:s:af:o:C", opt
, 0, 0, 0);
171 case 'k': kn
= optarg
; break;
172 case 's': skn
= optarg
; break;
173 case 'a': ef
= "pem"; break;
174 case 'f': ef
= optarg
; break;
175 case 'o': of
= optarg
; break;
176 case 'C': f
|= f_nocheck
; break;
177 default: f
|= f_bogus
; break;
180 if (argc
- optind
> 1 || (f
& f_bogus
))
181 die(EXIT_FAILURE
, "Usage: encrypt [-OPTIONS] [FILE]");
183 if (key_open(&kf
, keyring
, KOPEN_READ
, key_moan
, 0))
184 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
185 if ((k
= key_bytag(&kf
, kn
)) == 0)
186 die(EXIT_FAILURE
, "key `%s' not found", kn
);
187 if (skn
&& (sk
= key_bytag(&kf
, skn
)) == 0)
188 die(EXIT_FAILURE
, "key `%s' not found", skn
);
190 if ((eo
= getenc(ef
)) == 0)
191 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
195 else if (strcmp(argv
[optind
], "-") == 0) {
198 } else if ((fp
= fopen(argv
[optind
], "rb")) == 0) {
199 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
200 argv
[optind
], 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 ofp
, strerror(errno
));
213 e
= initenc(eo
, ofp
, "CATCRYPT ENCRYPTED MESSAGE");
214 km
= getkem(k
, "cckem", 0);
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
, &cx
, &c
, &m
))
240 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(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 assert(GC_CLASS(c
)->blksz
<= sizeof(bb
));
262 dstr_ensure(&d
, sizeof(bb
) + GM_CLASS(m
)->hashsz
);
264 chsz
= MASK16
- GM_CLASS(m
)->hashsz
;
269 if (GC_CLASS(c
)->blksz
) {
270 GC_ENCRYPT(cx
, 0, bb
, GC_CLASS(c
)->blksz
);
273 n
= fread(bb
, 1, chsz
, fp
);
275 buf_init(&b
, d
.buf
, d
.sz
);
276 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
278 assert(tag
); assert(ct
);
279 GC_ENCRYPT(c
, bb
, ct
, n
);
286 /* --- Final terminator packet --- */
288 buf_init(&b
, d
.buf
, d
.sz
);
289 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
295 /* --- All done --- */
304 if (fp
!= stdin
) fclose(fp
);
314 /*---- Decryption ---------------------------------------------------------*/
316 static int decrypt(int argc
, char *argv
[])
319 FILE *ofp
= 0, *rfp
= 0;
321 const char *ef
= "binary";
349 static const struct option opt
[] = {
350 { "armour", 0, 0, 'a' },
351 { "armor", 0, 0, 'a' },
352 { "buffer", 0, 0, 'b' },
353 { "verbose", 0, 0, 'v' },
354 { "quiet", 0, 0, 'q' },
355 { "nocheck", 0, 0, 'C' },
356 { "format", OPTF_ARGREQ
, 0, 'f' },
357 { "output", OPTF_ARGREQ
, 0, 'o' },
360 i
= mdwopt(argc
, argv
, "abf:o:qvC", opt
, 0, 0, 0);
363 case 'a': ef
= "pem"; break;
364 case 'b': f
|= f_buffer
; break;
365 case 'v': verb
++; break;
366 case 'q': if (verb
) verb
--; break;
367 case 'C': f
|= f_nocheck
; break;
368 case 'f': ef
= optarg
; break;
369 case 'o': of
= optarg
; break;
370 default: f
|= f_bogus
; break;
373 if (argc
- optind
> 1 || (f
& f_bogus
))
374 die(EXIT_FAILURE
, "Usage: decrypt [-OPTIONS] [FILE]");
376 if ((eo
= getenc(ef
)) == 0)
377 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
381 else if (strcmp(argv
[optind
], "-") == 0) {
384 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
385 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
386 argv
[optind
], strerror(errno
));
390 if (key_open(&kf
, keyring
, KOPEN_READ
, key_moan
, 0))
391 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
393 e
= initdec(eo
, fp
, checkbdry
, "CATCRYPT ENCRYPTED MESSAGE");
395 /* --- Read the header chunk --- */
397 chunk_read(e
, &d
, &b
);
398 if (buf_getu32(&b
, &id
)) {
399 if (verb
) printf("FAIL malformed header: missing keyid\n");
402 if ((k
= key_byid(&kf
, id
)) == 0) {
403 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
407 if (buf_getu32(&b
, &id
)) {
408 if (verb
) printf("FAIL malformed header: missing signature keyid\n");
411 if ((sk
= key_byid(&kf
, id
)) == 0) {
412 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
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);
434 /* --- Read the KEM chunk --- */
436 chunk_read(e
, &d
, &b
);
437 if (setupkem(km
, &d
, &cx
, &c
, &m
)) {
438 if (verb
) printf("FAIL failed to decapsulate key\n");
441 if (s
) GH_HASHBUF16(s
->h
, d
.buf
, d
.len
);
443 /* --- Verify the signature, if there is one --- */
447 dstr_ensure(&d
, 1024);
448 GC_ENCRYPT(cx
, 0, d
.buf
, 1024);
449 GH_HASH(s
->h
, d
.buf
, 1024);
450 chunk_read(e
, &d
, &b
);
451 if (s
->ops
->doit(s
, &d
)) {
452 if (verb
) printf("FAIL signature verification failed\n");
458 printf("INFO good-signature %s\n", d
.buf
);
462 printf("INFO no-signature\n");
464 /* --- Now decrypt the main body --- */
466 if (!of
|| strcmp(of
, "-") == 0) {
470 if (!(f
& f_buffer
)) {
471 if ((ofp
= fopen(of
, "wb")) == 0) {
472 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
473 ofp
, strerror(errno
));
476 } else if ((rfp
= tmpfile()) == 0)
477 die(EXIT_FAILURE
, "couldn't create temporary file: %s", strerror(errno
));
480 dstr_ensure(&d
, GC_CLASS(c
)->blksz
);
483 if (GC_CLASS(c
)->blksz
) {
484 GC_ENCRYPT(cx
, 0, d
.buf
, GC_CLASS(c
)->blksz
);
490 chunk_read(e
, &d
, &b
);
491 if ((tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
)) == 0) {
492 if (verb
) printf("FAIL bad ciphertext chunk: no tag\n");
495 GH_HASH(h
, BCUR(&b
), BLEFT(&b
));
496 if (memcmp(tag
, GH_DONE(h
, 0), GM_CLASS(m
)->hashsz
) != 0) {
498 printf("FAIL bad ciphertext chunk: authentication failure\n");
504 GC_DECRYPT(c
, BCUR(&b
), BCUR(&b
), BLEFT(&b
));
505 if (fwrite(BCUR(&b
), 1, BLEFT(&b
), rfp
) != BLEFT(&b
)) {
506 if (verb
) printf("FAIL error writing output: %s\n", strerror(errno
));
511 if (fflush(rfp
) || ferror(rfp
)) {
512 if (verb
) printf("FAIL error writing output: %s\n", strerror(errno
));
516 if (!ofp
&& (ofp
= fopen(of
, "wb")) == 0) {
517 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
518 of
, strerror(errno
));
522 dstr_ensure(&d
, 65536);
523 if (verb
&& ofp
== stdout
) printf("DATA\n");
525 n
= fread(d
.buf
, 1, d
.sz
, rfp
);
527 if (fwrite(d
.buf
, 1, n
, ofp
) < n
)
528 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
530 if (ferror(rfp
) || fclose(rfp
))
531 die(EXIT_FAILURE
, "error unbuffering output: %s", strerror(errno
));
533 if (ofp
&& (fflush(ofp
) || ferror(ofp
) || fclose(ofp
)))
534 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
537 if (verb
&& ofp
!= stdout
)
538 printf("OK decrypted successfully\n");
544 if (fp
!= stdin
) fclose(fp
);
555 /*----- Main code ---------------------------------------------------------*/
559 listtab[i].name, listtab[i].name) \
560 LI("Key-encapsulation mechanisms", kem, \
561 kemtab[i].name, kemtab[i].name) \
562 LI("Signature schemes", sig, \
563 sigtab[i].name, sigtab[i].name) \
564 LI("Encodings", enc, \
565 enctab[i].name, enctab[i].name) \
566 LI("Symmetric encryption algorithms", cipher, \
567 gciphertab[i], gciphertab[i]->name) \
568 LI("Hash functions", hash, \
569 ghashtab[i], ghashtab[i]->name) \
570 LI("Message authentication codes", mac, \
571 gmactab[i], gmactab[i]->name)
573 MAKELISTTAB(listtab
, LISTS
)
575 int cmd_show(int argc
, char *argv
[])
577 return (displaylists(listtab
, argv
+ 1));
580 static int cmd_help(int, char **);
582 static cmd cmdtab
[] = {
583 { "help", cmd_help
, "help [COMMAND...]" },
584 { "show", cmd_show
, "show [ITEM...]" },
587 { "encrypt", encrypt
,
588 "encrypt [-aC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
589 [-o OUTPUT] [FILE]", "\
592 -a, --armour Same as `-f pem'.\n\
593 -f, --format=FORMAT Encode as FORMAT.\n\
594 -k, --key=TAG Use public encryption key named by TAG.\n\
595 -s, --sign-key=TAG Use private signature key named by TAG.\n\
596 -o, --output=FILE Write output to FILE.\n\
597 -C, --nocheck Don't check the public key.\n\
599 { "decrypt", decrypt
,
600 "decrypt [-abqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
603 -a, --armour Same as `-f pem'.\n\
604 -b, --buffer Buffer output until we're sure we have it all.\n\
605 -f, --format=FORMAT Decode as FORMAT.\n\
606 -o, --output=FILE Write output to FILE.\n\
607 -q, --quiet Produce fewer messages.\n\
608 -v, --verbose Produce more verbose messages.\n\
609 -C, --nocheck Don't check the private key.\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 -------------------------------------------------*/