X-Git-Url: https://git.distorted.org.uk/u/mdw/catacomb/blobdiff_plain/72a6efc4d59568868fc6bbe05d343f777fc1a159..5c3f75ec49019d160806489824fc76652a2ef444:/catcrypt.c diff --git a/catcrypt.c b/catcrypt.c new file mode 100644 index 0000000..1ffae77 --- /dev/null +++ b/catcrypt.c @@ -0,0 +1,757 @@ +/* -*-c-*- + * + * $Id: catcrypt.c,v 1.1 2004/04/17 09:58:36 mdw Exp $ + * + * Command-line encryption tool + * + * (c) 2004 Straylight/Edgeware + */ + +/*----- Licensing notice --------------------------------------------------* + * + * This file is part of Catacomb. + * + * Catacomb is free software; you can redistribute it and/or modify + * it under the terms of the GNU Library General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * Catacomb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with Catacomb; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, + * MA 02111-1307, USA. + */ + +/*----- Header files ------------------------------------------------------*/ + +#include "config.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "buf.h" +#include "rand.h" +#include "noise.h" +#include "mprand.h" +#include "key.h" +#include "cc.h" + +/*----- Utilities ---------------------------------------------------------*/ + +/* --- @keyreport@ --- * + * + * Arguments: @const char *file@ = filename containing the error + * @int line@ = line number in file + * @const char *err@ = error text message + * @void *p@ = unimportant pointer + * + * Returns: --- + * + * Use: Reports errors during the opening of a key file. + */ + +static void keyreport(const char *file, int line, const char *err, void *p) +{ + moan("error in keyring `%s' at line `%s': %s", file, line, err); +} + +/*----- Static variables --------------------------------------------------*/ + +static const char *keyring = "keyring"; + +/*----- Data format -------------------------------------------------------*/ + +/* --- Overview --- * + * + * The encrypted message is divided into chunks, each preceded by a two-octet + * length. The chunks don't need to be large -- the idea is that we can + * stream the chunks in and out. + * + * The first chunk is a header. It contains the decryption key-id, and maybe + * the verification key-id if the message is signed. + * + * Next comes the key-encapsulation chunk. This is decrypted in some + * KEM-specific way to yield a secret hash. This hash is what is signed if + * the message is signed. The hash is expanded using an MGF (or similar) to + * make a symmetric encryption and MAC key. + * + * If the message is signed, there comes a signature chunk. The signature is + * on the secret hash. This means that the recipient can modify the message + * and still have a valid signature, so it's not useful for proving things to + * other people; but it also means that the recipient knows that the message + * is from someone who knows the hash, which limits the possiblities to (a) + * whoever encrypted the message (good!) and (b) whoever knows the + * recipient's private key. + * + * Then come message chunks. Each one begins with a MAC over an implicit + * sequence number and the ciphertext. The final chunk's ciphertext is + * empty; no other chunk is empty. Thus can the correct end-of-file be + * discerned. + */ + +/*----- Chunk I/O ---------------------------------------------------------*/ + +static void chunk_write(enc *e, buf *b) +{ + octet l[2]; + size_t n = BLEN(b); + assert(n <= MASK16); + STORE16(l, n); + if (e->ops->write(e, l, 2) || + e->ops->write(e, BBASE(b), BLEN(b))) + die(EXIT_FAILURE, "error writing output: %s", strerror(errno)); +} + +static void chunk_read(enc *e, dstr *d, buf *b) +{ + octet l[2]; + size_t n; + + dstr_reset(d); + errno = 0; + if (e->ops->read(e, l, 2) != 2) + goto err; + n = LOAD16(l); + dstr_ensure(d, n); + if (e->ops->read(e, d->buf, n) != n) + goto err; + d->len = n; + buf_init(b, d->buf, d->len); + return; + +err: + if (!errno) die(EXIT_FAILURE, "unexpected end-of-file on input"); + else die(EXIT_FAILURE, "error reading input: %s", strerror(errno)); +} + +/*----- Encryption --------------------------------------------------------*/ + +static int encrypt(int argc, char *argv[]) +{ + const char *of = 0, *kn = "ccrypt"; + FILE *ofp = 0; + FILE *fp = 0; + const char *ef = "binary"; + const char *err; + int i; + size_t n; + dstr d = DSTR_INIT; + octet *tag, *ct; + buf b; + size_t seq; + char bb[16384]; + unsigned f = 0; + key_file kf; + key *k; + kem *km; + gcipher *cx, *c; + gmac *m; + ghash *h; + const encops *eo; + enc *e; + +#define f_bogus 1u + + for (;;) { + static const struct option opt[] = { + { "key", OPTF_ARGREQ, 0, 'k' }, + { "armour", 0, 0, 'a' }, + { "armor", 0, 0, 'a' }, + { "format", OPTF_ARGREQ, 0, 'f' }, + { "output", OPTF_ARGREQ, 0, 'o' }, + { 0, 0, 0, 0 } + }; + i = mdwopt(argc, argv, "k:af:o:", opt, 0, 0, 0); + if (i < 0) break; + switch (i) { + case 'k': kn = optarg; break; + case 'a': ef = "pem"; break; + case 'f': ef = optarg; break; + case 'o': of = optarg; break; + default: f |= f_bogus; break; + } + } + if (argc - optind > 1 || (f & f_bogus)) + die(EXIT_FAILURE, "Usage: encrypt [-options] [file]"); + + if (key_open(&kf, keyring, KOPEN_READ, keyreport, 0)) + die(EXIT_FAILURE, "can't open keyring `%s'", keyring); + if ((k = key_bytag(&kf, kn)) == 0) + die(EXIT_FAILURE, "key `%s' not found", kn); + + if ((eo = getenc(ef)) == 0) + die(EXIT_FAILURE, "encoding `%s' not found", ef); + + if (optind == argc) + fp = stdin; + else if (strcmp(argv[optind], "-") == 0) { + fp = stdin; + optind++; + } else if ((fp = fopen(argv[optind], "rb")) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s': %s", + argv[optind], strerror(errno)); + } else + optind++; + + if (!of || strcmp(of, "-") == 0) + ofp = stdout; + else if ((ofp = fopen(of, eo->wmode)) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s' for output: %s", + ofp, strerror(errno)); + } + + key_fulltag(k, &d); + e = initenc(eo, ofp, "CATCRYPT ENCRYPTED MESSAGE", 1); + km = getkem(k, "ccrypt", 0); + if ((err = km->ops->check(km)) != 0) + moan("key `%s' fails check: %s", d.buf, err); + + /* --- Build the header chunk --- */ + + dstr_reset(&d); + dstr_ensure(&d, 256); + buf_init(&b, d.buf, 256); + buf_putu32(&b, k->id); + assert(BOK(&b)); + chunk_write(e, &b); + + /* --- Build the KEM chunk --- */ + + dstr_reset(&d); + if (setupkem(km, &d, &cx, &c, &m)) + die(EXIT_FAILURE, "failed to encapsulate key"); + buf_init(&b, d.buf, d.len); + BSTEP(&b, d.len); + chunk_write(e, &b); + + /* --- Now do the main crypto --- */ + + assert(GC_CLASS(c)->blksz <= sizeof(bb)); + dstr_ensure(&d, sizeof(bb) + GM_CLASS(m)->hashsz); + seq = 0; + for (;;) { + h = GM_INIT(m); + STORE32(bb, seq); + GH_HASH(h, bb, 4); + seq++; + if (GC_CLASS(c)->blksz) { + GC_ENCRYPT(cx, 0, bb, GC_CLASS(c)->blksz); + GC_SETIV(c, bb); + } + n = fread(bb, 1, sizeof(bb), fp); + if (!n) break; + buf_init(&b, d.buf, d.sz); + tag = buf_get(&b, GM_CLASS(m)->hashsz); + ct = buf_get(&b, n); + assert(tag); assert(ct); + GC_ENCRYPT(c, bb, ct, n); + GH_HASH(h, ct, n); + GH_DONE(h, tag); + GH_DESTROY(h); + chunk_write(e, &b); + } + + /* --- Final terminator packet --- */ + + buf_init(&b, d.buf, d.sz); + tag = buf_get(&b, GM_CLASS(m)->hashsz); + assert(tag); + GH_DONE(h, tag); + GH_DESTROY(h); + chunk_write(e, &b); + + /* --- All done --- */ + + e->ops->encdone(e); + GM_DESTROY(m); + GC_DESTROY(c); + GC_DESTROY(cx); + freeenc(e); + freekem(km); + if (of) fclose(ofp); + key_close(&kf); + dstr_destroy(&d); + return (0); + +#undef f_bogus +} + +/*---- Decryption ---------------------------------------------------------*/ + +static int decrypt(int argc, char *argv[]) +{ + const char *of = 0; + FILE *ofp = 0; + FILE *fp = 0; + const char *ef = "binary"; + int i; + dstr d = DSTR_INIT; + buf b; + key_file kf; + size_t seq; + uint32 id; + key *k; + kem *km; + gcipher *cx; + gcipher *c; + ghash *h; + gmac *m; + octet *tag; + unsigned f = 0; + const encops *eo; + enc *e; + +#define f_bogus 1u + + for (;;) { + static const struct option opt[] = { + { "armour", 0, 0, 'a' }, + { "armor", 0, 0, 'a' }, + { "format", OPTF_ARGREQ, 0, 'f' }, + { "output", OPTF_ARGREQ, 0, 'o' }, + { 0, 0, 0, 0 } + }; + i = mdwopt(argc, argv, "af:o:", opt, 0, 0, 0); + if (i < 0) break; + switch (i) { + case 'a': ef = "pem"; break; + case 'f': ef = optarg; break; + case 'o': of = optarg; break; + default: f |= f_bogus; break; + } + } + if (argc - optind > 1 || (f & f_bogus)) + die(EXIT_FAILURE, "Usage: decrypt [-options] [file]"); + + if ((eo = getenc(ef)) == 0) + die(EXIT_FAILURE, "encoding `%s' not found", ef); + + if (optind == argc) + fp = stdin; + else if (strcmp(argv[optind], "-") == 0) { + fp = stdin; + optind++; + } else if ((fp = fopen(argv[optind], eo->rmode)) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s': %s", + argv[optind], strerror(errno)); + } else + optind++; + + if (key_open(&kf, keyring, KOPEN_READ, keyreport, 0)) + die(EXIT_FAILURE, "can't open keyring `%s'", keyring); + + e = initenc(eo, fp, "CATCRYPT ENCRYPTED MESSAGE", 0); + + /* --- Read the header chunk --- */ + + chunk_read(e, &d, &b); + if (buf_getu32(&b, &id)) + die(EXIT_FAILURE, "malformed header: missing keyid"); + if (BLEFT(&b)) + die(EXIT_FAILURE, "malformed header: junk at end"); + + /* --- Find the key --- */ + + if ((k = key_byid(&kf, id)) == 0) + die(EXIT_FAILURE, "key id %08lx not found", (unsigned long)id); + km = getkem(k, "ccrypt", 1); + + /* --- Read the KEM chunk --- */ + + chunk_read(e, &d, &b); + if (setupkem(km, &d, &cx, &c, &m)) + die(EXIT_FAILURE, "failed to decapsulate key"); + + /* --- Now decrypt the main body --- */ + + if (!of || strcmp(of, "-") == 0) + ofp = stdout; + else if ((ofp = fopen(of, "wb")) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s' for output: %s", + ofp, strerror(errno)); + } + + seq = 0; + dstr_ensure(&d, GC_CLASS(c)->blksz); + dstr_ensure(&d, 4); + for (;;) { + if (GC_CLASS(c)->blksz) { + GC_ENCRYPT(cx, 0, d.buf, GC_CLASS(c)->blksz); + GC_SETIV(c, d.buf); + } + h = GM_INIT(m); + STORE32(d.buf, seq); + GH_HASH(h, d.buf, 4); + seq++; + chunk_read(e, &d, &b); + if ((tag = buf_get(&b, GM_CLASS(m)->hashsz)) == 0) + die(EXIT_FAILURE, "bad ciphertext chunk: no tag"); + GH_HASH(h, BCUR(&b), BLEFT(&b)); + if (memcmp(tag, GH_DONE(h, 0), GM_CLASS(m)->hashsz) != 0) + die(EXIT_FAILURE, "bad ciphertext chunk: authentication failure"); + if (!BLEFT(&b)) + break; + GC_DECRYPT(c, BCUR(&b), BCUR(&b), BLEFT(&b)); + if (fwrite(BCUR(&b), 1, BLEFT(&b), ofp) != BLEFT(&b)) + die(EXIT_FAILURE, "error writing output: %s", strerror(errno)); + } + + if (fflush(ofp) || ferror(ofp)) + die(EXIT_FAILURE, "error writing output: %s", strerror(errno)); + + e->ops->decdone(e); + freeenc(e); + GC_DESTROY(c); + GC_DESTROY(cx); + GM_DESTROY(m); + freekem(km); + if (of) fclose(ofp); + key_close(&kf); + dstr_destroy(&d); + return (0); + +#undef f_bogus +} + +/*----- Test code ---------------------------------------------------------*/ + +static int encode(int argc, char *argv[]) +{ + const char *of = 0; + FILE *ofp = 0; + FILE *fp = 0; + const char *ef = "binary"; + const char *bd = "MESSAGE"; + int i; + size_t n; + char buf[4096]; + unsigned f = 0; + const encops *eo; + enc *e; + +#define f_bogus 1u + + for (;;) { + static const struct option opt[] = { + { "format", OPTF_ARGREQ, 0, 'f' }, + { "boundary", OPTF_ARGREQ, 0, 'b' }, + { "output", OPTF_ARGREQ, 0, 'o' }, + { 0, 0, 0, 0 } + }; + i = mdwopt(argc, argv, "f:b:o:", opt, 0, 0, 0); + if (i < 0) break; + switch (i) { + case 'f': ef = optarg; break; + case 'b': bd = optarg; break; + case 'o': of = optarg; break; + default: f |= f_bogus; break; + } + } + if (argc - optind > 1 || (f & f_bogus)) + die(EXIT_FAILURE, "Usage: encode [-options] [file]"); + + if ((eo = getenc(ef)) == 0) + die(EXIT_FAILURE, "encoding `%s' not found", ef); + + if (optind == argc) + fp = stdin; + else if (strcmp(argv[optind], "-") == 0) { + fp = stdin; + optind++; + } else if ((fp = fopen(argv[optind], "rb")) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s': %s", + argv[optind], strerror(errno)); + } else + optind++; + + if (!of || strcmp(of, "-") == 0) + ofp = stdout; + else if ((ofp = fopen(of, eo->wmode)) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s' for output: %s", + ofp, strerror(errno)); + } + + e = initenc(eo, ofp, bd, 1); + + do { + n = fread(buf, 1, sizeof(buf), fp); + if (e->ops->write(e, buf, n)) + die(EXIT_FAILURE, "error writing output: %s", strerror(errno)); + } while (n == sizeof(buf)); + e->ops->encdone(e); + freeenc(e); + return (0); + +#undef f_bogus +} + +static int decode(int argc, char *argv[]) +{ + const char *of = 0; + FILE *ofp = 0; + FILE *fp = 0; + const char *ef = "binary"; + const char *bd = 0; + int i; + char buf[4096]; + unsigned f = 0; + const encops *eo; + enc *e; + +#define f_bogus 1u + + for (;;) { + static const struct option opt[] = { + { "format", OPTF_ARGREQ, 0, 'f' }, + { "boundary", OPTF_ARGREQ, 0, 'b' }, + { "output", OPTF_ARGREQ, 0, 'o' }, + { 0, 0, 0, 0 } + }; + i = mdwopt(argc, argv, "f:b:o:", opt, 0, 0, 0); + if (i < 0) break; + switch (i) { + case 'f': ef = optarg; break; + case 'b': bd = optarg; break; + case 'o': of = optarg; break; + default: f |= f_bogus; break; + } + } + if (argc - optind > 1 || (f & f_bogus)) + die(EXIT_FAILURE, "Usage: decode [-options] [file]"); + + if ((eo = getenc(ef)) == 0) + die(EXIT_FAILURE, "encoding `%s' not found", ef); + + if (optind == argc) + fp = stdin; + else if (strcmp(argv[optind], "-") == 0) { + fp = stdin; + optind++; + } else if ((fp = fopen(argv[optind], eo->rmode)) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s': %s", + argv[optind], strerror(errno)); + } else + optind++; + + if (!of || strcmp(of, "-") == 0) + ofp = stdout; + else if ((ofp = fopen(of, "wb")) == 0) { + die(EXIT_FAILURE, "couldn't open file `%s' for output: %s", + ofp, strerror(errno)); + } + + e = initenc(eo, fp, bd, 0); + + do { + if ((i = e->ops->read(e, buf, sizeof(buf))) < 0) + die(EXIT_FAILURE, "error reading input: %s", strerror(errno)); + if (fwrite(buf, 1, i, ofp) < i) + die(EXIT_FAILURE, "error writing output: %s", strerror(errno)); + } while (i == sizeof(buf)); + e->ops->decdone(e); + freeenc(e); + return (0); + +#undef f_bogus +} + +/*----- Main code ---------------------------------------------------------*/ + +typedef struct cmd { + const char *name; + int (*func)(int /*argc*/, char */*argv*/[]); + const char *usage; + const char *help; +} cmd; + +static cmd cmdtab[] = { + { "encode", encode, + "encode [-f format] [-b label] [-o output] [file]", + "\ +Options:\n\ +\n\ +-f, --format=FORMAT Encode to FORMAT.\n\ +-b, --boundary=LABEL PEM boundary is LABEL.\n\ +-o, --output=FILE Write output to FILE.\n\ +" }, + { "decode", decode, + "decode [-f format] [-b label] [-o output] [file]", + "\ +Options:\n\ +\n\ +-f, --format=FORMAT Decode from FORMAT.\n\ +-b, --boundary=LABEL PEM boundary is LABEL.\n\ +-o, --output=FILE Write output to FILE.\n\ +" }, + { "encrypt", encrypt, + "encrypt [-a] [-k tag] [f format]] [-o output] [file]", + "\ +Options:\n\ +\n\ +-a, --armour Same as `-f pem'.\n\ +-f, --format=FORMAT Encode as FORMAT.\n\ +-k, --key=TAG Use public key named by TAG.\n\ +-o, --output=FILE Write output to FILE.\n\ +" }, + { "decrypt", decrypt, + "decrypt [-t] [-o output] [file]", "\ +Options:\n\ +\n\ +-t, --text Read PEM-encoded input.\n\ +-o, --output=FILE Write output to FILE.\n\ +" }, + { 0, 0, 0 } +}; + +/* --- @findcmd@ --- * + * + * Arguments: @const char *name@ = a command name + * + * Returns: Pointer to the command structure. + * + * Use: Looks up a command by name. If the command isn't found, an + * error is reported and the program is terminated. + */ + +static cmd *findcmd(const char *name) +{ + cmd *c, *chosen = 0; + size_t sz = strlen(name); + + for (c = cmdtab; c->name; c++) { + if (strncmp(name, c->name, sz) == 0) { + if (c->name[sz] == 0) { + chosen = c; + break; + } else if (chosen) + die(EXIT_FAILURE, "ambiguous command name `%s'", name); + else + chosen = c; + } + } + if (!chosen) + die(EXIT_FAILURE, "unknown command name `%s'", name); + return (chosen); +} + +static void version(FILE *fp) +{ + pquis(fp, "$, Catacomb version " VERSION "\n"); +} + +static void usage(FILE *fp) +{ + pquis(fp, "Usage: $ [-k keyring] command [args]\n"); +} + +static void help(FILE *fp, char **argv) +{ + cmd *c; + + if (*argv) { + c = findcmd(*argv); + fprintf(fp, "Usage: %s [-k keyring] %s\n", QUIS, c->usage); + if (c->help) { + fputc('\n', fp); + fputs(c->help, fp); + } + } else { + version(fp); + fputc('\n', fp); + usage(fp); + fputs("\n\ +Create and verify signatures on lists of files.\n\ +\n", fp); + for (c = cmdtab; c->name; c++) + fprintf(fp, "%s\n", c->usage); + } +} + +/* --- @main@ --- * + * + * Arguments: @int argc@ = number of command line arguments + * @char *argv[]@ = vector of command line arguments + * + * Returns: Zero if successful, nonzero otherwise. + * + * Use: Signs or verifies signatures on lists of files. Useful for + * ensuring that a distribution is unmolested. + */ + +int main(int argc, char *argv[]) +{ + unsigned f = 0; + +#define f_bogus 1u + + /* --- Initialize the library --- */ + + ego(argv[0]); + sub_init(); + rand_noisesrc(RAND_GLOBAL, &noise_source); + rand_seed(RAND_GLOBAL, 160); + + /* --- Parse options --- */ + + for (;;) { + static struct option opts[] = { + { "help", 0, 0, 'h' }, + { "version", 0, 0, 'v' }, + { "usage", 0, 0, 'u' }, + { "keyring", OPTF_ARGREQ, 0, 'k' }, + { 0, 0, 0, 0 } + }; + int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0); + if (i < 0) + break; + switch (i) { + case 'h': + help(stdout, argv + optind); + exit(0); + break; + case 'v': + version(stdout); + exit(0); + break; + case 'u': + usage(stdout); + exit(0); + case 'k': + keyring = optarg; + break; + default: + f |= f_bogus; + break; + } + } + + argc -= optind; + argv += optind; + optind = 0; + if (f & f_bogus || argc < 1) { + usage(stderr); + exit(EXIT_FAILURE); + } + + /* --- Dispatch to the correct subcommand handler --- */ + + return (findcmd(argv[0])->func(argc, argv)); + +#undef f_bogus +} + +/*----- That's all, folks -------------------------------------------------*/