5 * Verify signatures on distribuitions of files
7 * (c) 2000 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 ------------------------------------------------------*/
40 #include <mLib/alloc.h>
41 #include <mLib/base64.h>
42 #include <mLib/mdwopt.h>
43 #include <mLib/quis.h>
44 #include <mLib/report.h>
55 /*----- Data formatting ---------------------------------------------------*/
57 /* --- Binary data structure --- *
59 * The binary format, which is used for hashing and for the optional binary
60 * output, consists of a sequence of tagged blocks. The tag describes the
61 * format and meaining of the following data.
65 /* --- Block tags --- */
67 T_IDENT = 0, /* An identifying marker */
68 T_KEYID, /* Key identifier */
69 T_BEGIN, /* Begin hashing here */
70 T_COMMENT = T_BEGIN, /* A textual comment */
71 T_DATE, /* Creation date of signature */
72 T_EXPIRE, /* Expiry date of signature */
73 T_FILE, /* File and corresponding hash */
74 T_SIGNATURE, /* Final signature block */
76 /* --- Error messages --- */
84 /* --- Name translation table --- */
86 static const char *tagtab[] = {
88 "comment:", "date:", "expires:", "file:",
93 static const char *errtab[] = {
95 "Unexpected end-of-file",
96 "Binary object too large",
101 /* --- Memory representation of block types --- */
103 typedef struct block {
104 int tag; /* Type tag */
105 dstr d; /* String data */
106 dstr b; /* Binary data */
107 time_t t; /* Timestamp */
108 uint32 k; /* Keyid */
111 /* --- @getstring@ --- *
113 * Arguments: @FILE *fp@ = stream from which to read
114 * @dstr *d@ = destination string
115 * @unsigned raw@ = raw or cooked read
117 * Returns: Zero if OK, nonzero on end-of-file.
119 * Use: Reads a filename (or something similar) from a stream.
122 static int getstring(FILE *fp, dstr *d, unsigned raw)
127 /* --- Raw: just read exactly what's written up to a null byte --- */
130 if ((ch = getc(fp)) == EOF)
136 if ((ch = getc(fp)) == EOF)
143 /* --- Skip as far as whitespace --- *
145 * Also skip past comments.
153 do ch = getc(fp); while (ch != '\n' && ch != EOF);
159 /* --- If the character is a quote then read a quoted string --- */
171 /* --- Now read all sorts of interesting things --- */
175 /* --- Handle an escaped thing --- */
182 case 'a': ch = '\a'; break;
183 case 'b': ch = '\b'; break;
184 case 'f': ch = '\f'; break;
185 case 'n': ch = '\n'; break;
186 case 'r': ch = '\r'; break;
187 case 't': ch = '\t'; break;
188 case 'v': ch = '\v'; break;
195 /* --- If it's a quote or some other end marker then stop --- */
197 if (ch == q || (!q && isspace((unsigned char)ch)))
200 /* --- Otherwise contribute and continue --- */
203 if ((ch = getc(fp)) == EOF)
213 /* --- @putstring@ --- *
215 * Arguments: @FILE *fp@ = stream to write on
216 * @const char *p@ = pointer to text
217 * @unsigned raw@ = whether the string is to be written raw
221 * Use: Emits a string to a stream.
224 static void putstring(FILE *fp, const char *p, unsigned raw)
226 size_t sz = strlen(p);
230 /* --- Just write the string null terminated if raw --- */
233 fwrite(p, 1, sz + 1, fp);
237 /* --- Check for any dodgy characters --- */
240 for (q = p; *q; q++) {
241 if (isspace((unsigned char)*q)) {
250 /* --- Emit the string --- */
252 for (q = p; *q; q++) {
254 case '\a': fputc('\\', fp); fputc('a', fp); break;
255 case '\b': fputc('\\', fp); fputc('b', fp); break;
256 case '\f': fputc('\\', fp); fputc('f', fp); break;
257 case '\n': fputc('\\', fp); fputc('n', fp); break;
258 case '\r': fputc('\\', fp); fputc('r', fp); break;
259 case '\t': fputc('\\', fp); fputc('t', fp); break;
260 case '\v': fputc('\\', fp); fputc('v', fp); break;
261 case '`': fputc('\\', fp); fputc('`', fp); break;
262 case '\'': fputc('\\', fp); fputc('\'', fp); break;
263 case '\"': fputc('\\', fp); fputc('\"', fp); break;
276 /* --- @timestring@ --- *
278 * Arguments: @time_t t@ = a timestamp
279 * @dstr *d@ = a string to write on
283 * Use: Writes a textual representation of the timestamp to the
287 static void timestring(time_t t, dstr *d)
289 if (t == KEXP_FOREVER)
292 struct tm *tm = localtime(&t);
294 d->len += strftime(d->buf + d->len, 32, "%Y-%m-%d %H:%M:%S %Z", tm);
299 /* --- @breset@ --- *
301 * Arguments: @block *b@ = block to reset
305 * Use: Resets a block so that more stuff can be put in it.
308 static void breset(block *b)
319 * Arguments: @block *b@ = block to initialize
323 * Use: Initializes a block as something to read into.
326 static void binit(block *b)
333 /* --- @bdestroy@ --- *
335 * Arguments: @block *b@ = block to destroy
339 * Use: Destroys a block's contents.
342 static void bdestroy(block *b)
350 * Arguments: @block *b@ = pointer to block
351 * @FILE *fp@ = stream to read from
352 * @unsigned bin@ = binary switch
354 * Returns: Tag of block, or an error tag.
356 * Use: Reads a block from a stream.
359 static int bget(block *b, FILE *fp, unsigned bin)
363 /* --- Read the tag --- */
369 if (getstring(fp, &d, 0))
371 for (tag = 0; tagtab[tag]; tag++) {
372 if (strcmp(tagtab[tag], d.buf) == 0)
379 /* --- Decide what to do next --- */
385 /* --- Reading of strings --- */
389 if (getstring(fp, &b->d, bin))
393 /* --- Timestamps --- */
399 if (fread(buf, sizeof(buf), 1, fp) < 1)
401 b->t = ((time_t)(((LOAD32(buf + 0) << 16) << 16) & ~MASK32) |
402 (time_t)LOAD32(buf + 4));
404 if (getstring(fp, &b->d, 0))
406 if (strcmp(b->d.buf, "forever") == 0)
408 else if ((b->t = get_date(b->d.buf, 0)) == -1)
413 /* --- Key ids --- */
418 if (fread(buf, sizeof(buf), 1, fp) < 1)
422 if (getstring(fp, &b->d, 0))
424 b->k = strtoul(b->d.buf, 0, 16);
428 /* --- Reading of binary data --- */
435 if (fread(buf, sizeof(buf), 1, fp) < 1)
441 if (fread(b->b.buf + b->b.len, 1, sz, fp) < sz)
446 if (getstring(fp, &b->d, 0))
449 base64_decode(&b64, b->d.buf, b->d.len, &b->b);
450 base64_decode(&b64, 0, 0, &b->b);
453 if (tag == T_FILE && getstring(fp, &b->d, bin))
457 /* --- Anything else --- */
468 * Arguments: @block *b@ = pointer to block to emit
469 * @dstr *d@ = output buffer
473 * Use: Encodes a block in a binary format.
476 static void blob(block *b, dstr *d)
488 if (b->t == KEXP_FOREVER) {
489 STORE32(d->buf + d->len, 0xffffffff);
490 STORE32(d->buf + d->len + 4, 0xffffffff);
492 STORE32(d->buf + d->len, ((b->t & ~MASK32) >> 16) >> 16);
493 STORE32(d->buf + d->len + 4, b->t);
499 STORE32(d->buf + d->len, b->k);
505 STORE16(d->buf + d->len, b->b.len);
508 if (b->tag == T_FILE) {
516 /* --- @bwrite@ --- *
518 * Arguments: @block *b@ = pointer to block to write
519 * @FILE *fp@ = stream to write on
523 * Use: Writes a block on a stream in a textual format.
526 static void bwrite(block *b, FILE *fp)
528 fputs(tagtab[b->tag], fp);
533 putstring(fp, b->d.buf, 0);
538 timestring(b->t, &d);
539 putstring(fp, d.buf, 0);
543 fprintf(fp, "%08lx", (unsigned long)b->k);
551 base64_encode(&b64, b->b.buf, b->b.len, &d);
552 base64_encode(&b64, 0, 0, &d);
554 if (b->tag == T_FILE) {
556 putstring(fp, b->d.buf, 0);
565 * Arguments: @block *b@ = pointer to block to write
566 * @FILE *fp@ = file to write on
567 * @ghash *h@ = pointer to hash function
568 * @unsigned bin@ = binary/text flag
572 * Use: Spits out a block properly.
575 static void bemit(block *b, FILE *fp, ghash *h, unsigned bin)
577 if (h || (fp && bin)) {
581 GH_HASH(h, d.buf, d.len);
583 fwrite(d.buf, d.len, 1, fp);
589 /*----- Static variables --------------------------------------------------*/
591 static const char *keyring = "keyring";
593 /*----- Other shared functions --------------------------------------------*/
597 * Arguments: @const gchash *c@ = pointer to hash class
598 * @const char *file@ = file to hash
599 * @void *b@ = pointer to output buffer
601 * Returns: Zero if it worked, or nonzero for a system error.
603 * Use: Hashes a file.
606 static int fhash(const gchash *c, const char *file, void *b)
608 FILE *fp = fopen(file, "rb");
609 ghash *h = GH_INIT(c);
616 while ((sz = fread(buf, 1, sizeof(buf), fp)) > 0)
628 * Arguments: @FILE *fp@ = file to write on
629 * @const void *p@ = pointer to data to be written
630 * @size_t sz@ = size of the data to write
634 * Use: Emits a hex dump to a stream.
637 static void fhex(FILE *fp, const void *p, size_t sz)
643 fprintf(fp, "%02x", *q++);
650 /*----- Signature generation ----------------------------------------------*/
652 static int sign(int argc, char *argv[])
660 const char *ki = "dsig";
664 time_t exp = KEXP_EXPIRE;
666 const char *ifile = 0;
667 const char *ofile = 0;
676 static struct option opts[] = {
677 { "null", 0, 0, '0' },
678 { "binary", 0, 0, 'b' },
679 { "verbose", 0, 0, 'v' },
680 { "quiet", 0, 0, 'q' },
681 { "comment", OPTF_ARGREQ, 0, 'c' },
682 { "file", OPTF_ARGREQ, 0, 'f' },
683 { "output", OPTF_ARGREQ, 0, 'o' },
684 { "key", OPTF_ARGREQ, 0, 'k' },
685 { "expire", OPTF_ARGREQ, 0, 'e' },
686 { "nocheck", OPTF_ARGREQ, 0, 'C' },
689 int i = mdwopt(argc, argv, "+0vqbC" "c:" "f:o:" "k:e:", opts, 0, 0, 0);
722 if (strcmp(optarg, "forever") == 0)
724 else if ((exp = get_date(optarg, 0)) == -1)
725 die(EXIT_FAILURE, "bad expiry time");
732 if (optind != argc || (f & f_bogus))
733 die(EXIT_FAILURE, "Usage: sign [-OPTIONS]");
735 /* --- Locate the signing key --- */
737 if (key_open(&kf, keyring, KOPEN_WRITE, key_moan, 0))
738 die(EXIT_FAILURE, "couldn't open keyring `%s'", keyring);
739 if ((k = key_bytag(&kf, ki)) == 0)
740 die(EXIT_FAILURE, "couldn't find key `%s'", ki);
742 if (exp == KEXP_FOREVER && k->exp != KEXP_FOREVER) {
743 die(EXIT_FAILURE, "key `%s' expires: can't create nonexpiring signature",
746 s = getsig(k, "dsig", 1);
748 /* --- Check the key --- */
750 if (!(f & f_nocheck) && (err = s->ops->check(s)) != 0)
751 moan("key `%s' fails check: %s", d.buf, err);
753 /* --- Open files --- */
757 else if ((ifp = fopen(ifile, (f & f_raw) ? "rb" : "r")) == 0) {
758 die(EXIT_FAILURE, "couldn't open input file `%s': %s",
759 ifile, strerror(errno));
764 else if ((ofp = fopen(ofile, (f & f_bin) ? "wb" : "w")) == 0) {
765 die(EXIT_FAILURE, "couldn't open output file `%s': %s",
766 ofile, strerror(errno));
769 /* --- Emit the start of the output --- */
771 binit(&b); b.tag = T_IDENT;
772 dstr_putf(&b.d, "%s, Catacomb version " VERSION, QUIS);
773 bemit(&b, ofp, 0, f & f_bin);
775 breset(&b); b.tag = T_KEYID; b.k = k->id;
776 bemit(&b, ofp, 0, f & f_bin);
778 /* --- Start hashing, and emit the datestamps and things --- */
781 time_t now = time(0);
783 breset(&b); b.tag = T_DATE; b.t = now; bemit(&b, ofp, s->h, f & f_bin);
784 if (exp == KEXP_EXPIRE)
785 exp = now + 86400 * 28;
786 breset(&b); b.tag = T_EXPIRE; b.t = exp; bemit(&b, ofp, s->h, f & f_bin);
788 breset(&b); b.tag = T_COMMENT; DPUTS(&b.d, c);
789 bemit(&b, ofp, s->h, f & f_bin);
796 /* --- Now hash the various files --- */
800 /* --- Stop on an output error --- */
807 /* --- Read the next filename to hash --- */
810 if (getstring(ifp, &b.d, f & f_raw))
813 DENSURE(&b.b, GH_CLASS(s->h)->hashsz);
814 if (fhash(GH_CLASS(s->h), b.d.buf, b.b.buf)) {
815 moan("Error reading `%s': %s", b.d.buf, strerror(errno));
818 b.b.len += GH_CLASS(s->h)->hashsz;
820 fhex(stderr, b.b.buf, b.b.len);
821 fprintf(stderr, " %s\n", b.d.buf);
823 bemit(&b, ofp, s->h, f & f_bin);
827 /* --- Create the signature --- */
829 if (!(f & f_bogus)) {
832 if ((e = s->ops->doit(s, &b.b)) != 0) {
833 moan("error creating signature: %s", key_strerror(e));
836 if (!(f & f_bogus)) {
837 bemit(&b, ofp, 0, f & f_bin);
838 key_used(&kf, k, exp);
842 /* --- Tidy up at the end --- */
855 if ((e = key_close(&kf)) != 0) {
858 die(EXIT_FAILURE, "couldn't write file `%s': %s",
859 keyring, strerror(errno));
861 die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
862 keyring, strerror(errno));
866 die(EXIT_FAILURE, "error(s) occurred while creating signature");
867 return (EXIT_SUCCESS);
875 /*----- Signature verification --------------------------------------------*/
877 static int verify(int argc, char *argv[])
895 /* --- Parse the options --- */
898 static struct option opts[] = {
899 { "verbose", 0, 0, 'v' },
900 { "quiet", 0, 0, 'q' },
901 { "nocheck", 0, 0, 'C' },
904 int i = mdwopt(argc, argv, "+vqC", opts, 0, 0, 0);
925 if ((f & f_bogus) || argc > 1)
926 die(EXIT_FAILURE, "Usage: verify [-qvC] [FILE]");
928 /* --- Open the key file, and start reading the input file --- */
930 if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
931 die(EXIT_FAILURE, "couldn't open keyring `%s'\n", keyring);
935 if ((fp = fopen(argv[0], "rb")) == 0) {
936 die(EXIT_FAILURE, "couldn't open file `%s': %s\n",
937 argv[0], strerror(errno));
944 if ((fp = fopen(argv[0], "r")) == 0) {
945 die(EXIT_FAILURE, "couldn't open file `%s': %s\n",
946 argv[0], strerror(errno));
951 /* --- Read the introductory matter --- */
956 e = bget(&b, fp, f & f_bin);
958 die(EXIT_FAILURE, "error reading packet: %s", errtab[-e]);
964 printf("INFO ident: `%s'\n", b.d.buf);
967 if ((k = key_byid(&kf, b.k)) == 0) {
969 printf("FAIL key %08lx not found\n", (unsigned long)b.k);
974 key_fulltag(k, &b.d);
975 printf("INFO key: %s\n", b.d.buf);
979 die(EXIT_FAILURE, "(internal) unknown packet type\n");
984 /* --- Initialize the hash function and start reading hashed packets --- */
988 puts("FAIL no keyid packet found");
992 s = getsig(k, "dsig", 0);
993 if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0)
994 printf("WARN public key fails check: %s", err);
1000 printf("INFO comment: `%s'\n", b.d.buf);
1001 bemit(&b, 0, s->h, 0);
1006 timestring(b.t, &b.d);
1007 printf("INFO date: %s\n", b.d.buf);
1009 bemit(&b, 0, s->h, 0);
1012 time_t now = time(0);
1013 if (b.t != KEXP_FOREVER && b.t < now) {
1015 puts("BAD signature has expired");
1020 timestring(b.t, &b.d);
1021 printf("INFO expires: %s\n", b.d.buf);
1023 bemit(&b, 0, s->h, 0);
1027 DENSURE(&d, GH_CLASS(s->h)->hashsz);
1028 if (fhash(GH_CLASS(s->h), b.d.buf, d.buf)) {
1030 printf("BAD error reading file `%s': %s\n",
1031 b.d.buf, strerror(errno));
1034 } else if (b.b.len != GH_CLASS(s->h)->hashsz ||
1035 memcmp(d.buf, b.b.buf, b.b.len) != 0) {
1037 printf("BAD file `%s' has incorrect hash\n", b.d.buf);
1039 } else if (verb > 3) {
1040 fputs("INFO hash: ", stdout);
1041 fhex(stdout, b.b.buf, b.b.len);
1042 printf(" %s\n", b.d.buf);
1044 bemit(&b, 0, s->h, 0);
1047 if (s->ops->doit(s, &b.b)) {
1049 puts("BAD bad signature");
1051 } else if (verb > 2)
1052 puts("INFO good signature");
1056 printf("FAIL invalid packet type %i\n", e);
1061 e = bget(&b, fp, f & f_bin);
1064 printf("FAIL error reading packet: %s\n", errtab[-e]);
1077 puts("FAIL signature invalid");
1079 puts("OK signature verified");
1081 return (f & f_bogus ? EXIT_FAILURE : EXIT_SUCCESS);
1089 /*----- Main code ---------------------------------------------------------*/
1093 listtab[i].name, listtab[i].name) \
1094 LI("Signature schemes", sig, \
1095 sigtab[i].name, sigtab[i].name) \
1096 LI("Hash functions", hash, \
1097 ghashtab[i], ghashtab[i]->name)
1099 MAKELISTTAB(listtab, LISTS)
1101 int cmd_show(int argc, char *argv[])
1103 return (displaylists(listtab, argv + 1));
1106 static int cmd_help(int, char **);
1108 static cmd cmdtab[] = {
1109 { "help", cmd_help, "help [COMMAND...]" },
1110 { "show", cmd_show, "show [ITEM...]" },
1112 "sign [-0bqvC] [-c COMMENT] [-k TAG] [-e EXPIRE]\n\t\
1113 [-f FILE] [-o OUTPUT]",
1117 -0, --null Read null-terminated filenames from stdin.\n\
1118 -b, --binary Produce a binary output file.\n\
1119 -q, --quiet Produce fewer messages while working.\n\
1120 -v, --verbose Produce more messages while working.\n\
1121 -C, --nocheck Don't check the private key.\n\
1122 -c, --comment=COMMENT Include COMMENT in the output file.\n\
1123 -f, --file=FILE Read filenames to hash from FILE.\n\
1124 -o, --output=FILE Write the signed result to FILE.\n\
1125 -k, --key=TAG Use a key named by TAG.\n\
1126 -e, --expire=TIME The signature should expire after TIME.\n\
1129 "verify [-qvC] [FILE]", "\
1132 -q, --quiet Produce fewer messages while working.\n\
1133 -v, --verbose Produce more messages while working.\n\
1134 -C, --nocheck Don't check the public key.\n\
1139 static int cmd_help(int argc, char **argv)
1141 sc_help(cmdtab, stdout, argv + 1);
1145 void version(FILE *fp)
1147 pquis(fp, "$, Catacomb version " VERSION "\n");
1150 static void usage(FILE *fp)
1152 pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
1155 void help_global(FILE *fp)
1159 Create and verify signatures on lists of files.\n\
1161 Global command-line options:\n\
1163 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
1164 -v, --version Show program version number.\n\
1165 -u, --usage Show a terse usage message.\n\
1167 -k, --keyring=FILE Read keys from FILE.\n",
1173 * Arguments: @int argc@ = number of command line arguments
1174 * @char *argv[]@ = vector of command line arguments
1176 * Returns: Zero if successful, nonzero otherwise.
1178 * Use: Signs or verifies signatures on lists of files. Useful for
1179 * ensuring that a distribution is unmolested.
1182 int main(int argc, char *argv[])
1188 /* --- Initialize the library --- */
1192 rand_noisesrc(RAND_GLOBAL, &noise_source);
1193 rand_seed(RAND_GLOBAL, 160);
1195 /* --- Parse options --- */
1198 static struct option opts[] = {
1199 { "help", 0, 0, 'h' },
1200 { "version", 0, 0, 'v' },
1201 { "usage", 0, 0, 'u' },
1202 { "keyring", OPTF_ARGREQ, 0, 'k' },
1205 int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
1210 sc_help(cmdtab, stdout, argv + optind);
1232 if (f & f_bogus || argc < 1) {
1237 /* --- Dispatch to the correct subcommand handler --- */
1239 return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
1244 /*----- That's all, folks -------------------------------------------------*/