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
);
268 if (GC_CLASS(c
)->blksz
) {
269 GC_ENCRYPT(cx
, 0, bb
, GC_CLASS(c
)->blksz
);
272 n
= fread(bb
, 1, sizeof(bb
), fp
);
274 buf_init(&b
, d
.buf
, d
.sz
);
275 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
277 assert(tag
); assert(ct
);
278 GC_ENCRYPT(c
, bb
, ct
, n
);
285 /* --- Final terminator packet --- */
287 buf_init(&b
, d
.buf
, d
.sz
);
288 tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
);
294 /* --- All done --- */
303 if (fp
!= stdin
) fclose(fp
);
313 /*---- Decryption ---------------------------------------------------------*/
315 static int decrypt(int argc
, char *argv
[])
318 FILE *ofp
= 0, *rfp
= 0;
320 const char *ef
= "binary";
348 static const struct option opt
[] = {
349 { "armour", 0, 0, 'a' },
350 { "armor", 0, 0, 'a' },
351 { "buffer", 0, 0, 'b' },
352 { "verbose", 0, 0, 'v' },
353 { "quiet", 0, 0, 'q' },
354 { "nocheck", 0, 0, 'C' },
355 { "format", OPTF_ARGREQ
, 0, 'f' },
356 { "output", OPTF_ARGREQ
, 0, 'o' },
359 i
= mdwopt(argc
, argv
, "abf:o:qvC", opt
, 0, 0, 0);
362 case 'a': ef
= "pem"; break;
363 case 'b': f
|= f_buffer
; break;
364 case 'v': verb
++; break;
365 case 'q': if (verb
) verb
--; break;
366 case 'C': f
|= f_nocheck
; break;
367 case 'f': ef
= optarg
; break;
368 case 'o': of
= optarg
; break;
369 default: f
|= f_bogus
; break;
372 if (argc
- optind
> 1 || (f
& f_bogus
))
373 die(EXIT_FAILURE
, "Usage: decrypt [-OPTIONS] [FILE]");
375 if ((eo
= getenc(ef
)) == 0)
376 die(EXIT_FAILURE
, "encoding `%s' not found", ef
);
380 else if (strcmp(argv
[optind
], "-") == 0) {
383 } else if ((fp
= fopen(argv
[optind
], eo
->rmode
)) == 0) {
384 die(EXIT_FAILURE
, "couldn't open file `%s': %s",
385 argv
[optind
], strerror(errno
));
389 if (key_open(&kf
, keyring
, KOPEN_READ
, key_moan
, 0))
390 die(EXIT_FAILURE
, "can't open keyring `%s'", keyring
);
392 e
= initdec(eo
, fp
, checkbdry
, "CATCRYPT ENCRYPTED MESSAGE");
394 /* --- Read the header chunk --- */
396 chunk_read(e
, &d
, &b
);
397 if (buf_getu32(&b
, &id
)) {
398 if (verb
) printf("FAIL malformed header: missing keyid\n");
401 if ((k
= key_byid(&kf
, id
)) == 0) {
402 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
406 if (buf_getu32(&b
, &id
)) {
407 if (verb
) printf("FAIL malformed header: missing signature keyid\n");
410 if ((sk
= key_byid(&kf
, id
)) == 0) {
411 if (verb
) printf("FAIL key id %08lx not found\n", (unsigned long)id
);
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);
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");
440 if (s
) GH_HASHBUF16(s
->h
, d
.buf
, d
.len
);
442 /* --- Verify the signature, if there is one --- */
446 dstr_ensure(&d
, 1024);
447 GC_ENCRYPT(cx
, 0, d
.buf
, 1024);
448 GH_HASH(s
->h
, d
.buf
, 1024);
449 chunk_read(e
, &d
, &b
);
450 if (s
->ops
->doit(s
, &d
)) {
451 if (verb
) printf("FAIL signature verification failed\n");
457 printf("INFO good-signature %s\n", d
.buf
);
461 printf("INFO no-signature\n");
463 /* --- Now decrypt the main body --- */
465 if (!of
|| strcmp(of
, "-") == 0) {
469 if (!(f
& f_buffer
)) {
470 if ((ofp
= fopen(of
, "wb")) == 0) {
471 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
472 ofp
, strerror(errno
));
475 } else if ((rfp
= tmpfile()) == 0)
476 die(EXIT_FAILURE
, "couldn't create temporary file: %s", strerror(errno
));
479 dstr_ensure(&d
, GC_CLASS(c
)->blksz
);
482 if (GC_CLASS(c
)->blksz
) {
483 GC_ENCRYPT(cx
, 0, d
.buf
, GC_CLASS(c
)->blksz
);
489 chunk_read(e
, &d
, &b
);
490 if ((tag
= buf_get(&b
, GM_CLASS(m
)->hashsz
)) == 0) {
491 if (verb
) printf("FAIL bad ciphertext chunk: no tag\n");
494 GH_HASH(h
, BCUR(&b
), BLEFT(&b
));
495 if (memcmp(tag
, GH_DONE(h
, 0), GM_CLASS(m
)->hashsz
) != 0) {
497 printf("FAIL bad ciphertext chunk: authentication failure\n");
503 GC_DECRYPT(c
, BCUR(&b
), BCUR(&b
), BLEFT(&b
));
504 if (fwrite(BCUR(&b
), 1, BLEFT(&b
), rfp
) != BLEFT(&b
)) {
505 if (verb
) printf("FAIL error writing output: %s\n", strerror(errno
));
510 if (fflush(rfp
) || ferror(rfp
)) {
511 if (verb
) printf("FAIL error writing output: %s\n", strerror(errno
));
515 if (!ofp
&& (ofp
= fopen(of
, "wb")) == 0) {
516 die(EXIT_FAILURE
, "couldn't open file `%s' for output: %s",
517 of
, strerror(errno
));
521 dstr_ensure(&d
, 65536);
522 if (verb
&& ofp
== stdout
) printf("DATA\n");
524 n
= fread(d
.buf
, 1, d
.sz
, rfp
);
526 if (fwrite(d
.buf
, 1, n
, ofp
) < n
)
527 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
529 if (ferror(rfp
) || fclose(rfp
))
530 die(EXIT_FAILURE
, "error unbuffering output: %s", strerror(errno
));
532 if (ofp
&& (fflush(ofp
) || ferror(ofp
) || fclose(ofp
)))
533 die(EXIT_FAILURE
, "error writing output: %s", strerror(errno
));
536 if (verb
&& ofp
!= stdout
)
537 printf("OK decrypted successfully\n");
543 if (fp
!= stdin
) fclose(fp
);
554 /*----- Main code ---------------------------------------------------------*/
558 listtab[i].name, listtab[i].name) \
559 LI("Key-encapsulation mechanisms", kem, \
560 kemtab[i].name, kemtab[i].name) \
561 LI("Signature schemes", sig, \
562 sigtab[i].name, sigtab[i].name) \
563 LI("Encodings", enc, \
564 enctab[i].name, enctab[i].name) \
565 LI("Symmetric encryption algorithms", cipher, \
566 gciphertab[i], gciphertab[i]->name) \
567 LI("Hash functions", hash, \
568 ghashtab[i], ghashtab[i]->name) \
569 LI("Message authentication codes", mac, \
570 gmactab[i], gmactab[i]->name)
572 MAKELISTTAB(listtab
, LISTS
)
574 int cmd_show(int argc
, char *argv
[])
576 return (displaylists(listtab
, argv
+ 1));
579 static int cmd_help(int, char **);
581 static cmd cmdtab
[] = {
582 { "help", cmd_help
, "help [COMMAND...]" },
583 { "show", cmd_show
, "show [ITEM...]" },
586 { "encrypt", encrypt
,
587 "encrypt [-aC] [-k TAG] [-s TAG] [-f FORMAT]\n\t\
588 [-o OUTPUT] [FILE]", "\
591 -a, --armour Same as `-f pem'.\n\
592 -f, --format=FORMAT Encode as FORMAT.\n\
593 -k, --key=TAG Use public encryption key named by TAG.\n\
594 -s, --sign-key=TAG Use private signature key named by TAG.\n\
595 -o, --output=FILE Write output to FILE.\n\
596 -C, --nocheck Don't check the public key.\n\
598 { "decrypt", decrypt
,
599 "decrypt [-abqvC] [-f FORMAT] [-o OUTPUT] [FILE]", "\
602 -a, --armour Same as `-f pem'.\n\
603 -b, --buffer Buffer output until we're sure we have it all.\n\
604 -f, --format=FORMAT Decode as FORMAT.\n\
605 -o, --output=FILE Write output to FILE.\n\
606 -q, --quiet Produce fewer messages.\n\
607 -v, --verbose Produce more verbose messages.\n\
608 -C, --nocheck Don't check the private key.\n\
609 " }, /* ' emacs is confused */
613 static int cmd_help(int argc
, char **argv
)
615 sc_help(cmdtab
, stdout
, argv
+ 1);
619 void version(FILE *fp
)
621 pquis(fp
, "$, Catacomb version " VERSION
"\n");
624 static void usage(FILE *fp
)
626 pquis(fp
, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
629 void help_global(FILE *fp
)
633 Encrypt and decrypt files.\n\
635 Global command-line options:\n\
637 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
638 -v, --version Show program version number.\n\
639 -u, --usage Show a terse usage message.\n\
641 -k, --keyring=FILE Read keys from FILE.\n",
647 * Arguments: @int argc@ = number of command line arguments
648 * @char *argv[]@ = vector of command line arguments
650 * Returns: Zero if successful, nonzero otherwise.
652 * Use: Encrypts or decrypts files.
655 int main(int argc
, char *argv
[])
661 /* --- Initialize the library --- */
665 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
666 rand_seed(RAND_GLOBAL
, 160);
668 /* --- Parse options --- */
671 static struct option opts
[] = {
672 { "help", 0, 0, 'h' },
673 { "version", 0, 0, 'v' },
674 { "usage", 0, 0, 'u' },
675 { "keyring", OPTF_ARGREQ
, 0, 'k' },
678 int i
= mdwopt(argc
, argv
, "+hvu k:", opts
, 0, 0, 0);
683 sc_help(cmdtab
, stdout
, argv
+ optind
);
705 if (f
& f_bogus
|| argc
< 1) {
710 /* --- Dispatch to the correct subcommand handler --- */
712 return (findcmd(cmdtab
, argv
[0])->cmd(argc
, argv
));
717 /*----- That's all, folks -------------------------------------------------*/