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 --------------------------------------------*/
595 /* --- @keyreport@ --- *
597 * Arguments: @const char *file@ = filename containing the error
598 * @int line@ = line number in file
599 * @const char *err@ = error text message
600 * @void *p@ = unimportant pointer
604 * Use: Reports errors during the opening of a key file.
607 static void keyreport(const char *file
, int line
, const char *err
, void *p
)
609 moan("error in keyring `%s' at line `%s': %s", file
, line
, err
);
614 * Arguments: @const gchash *c@ = pointer to hash class
615 * @const char *file@ = file to hash
616 * @void *b@ = pointer to output buffer
618 * Returns: Zero if it worked, or nonzero for a system error.
620 * Use: Hashes a file.
623 static int fhash(const gchash
*c
, const char *file
, void *b
)
625 FILE *fp
= fopen(file
, "rb");
626 ghash
*h
= GH_INIT(c
);
633 while ((sz
= fread(buf
, 1, sizeof(buf
), fp
)) > 0)
645 * Arguments: @FILE *fp@ = file to write on
646 * @const void *p@ = pointer to data to be written
647 * @size_t sz@ = size of the data to write
651 * Use: Emits a hex dump to a stream.
654 static void fhex(FILE *fp
, const void *p
, size_t sz
)
660 fprintf(fp
, "%02x", *q
++);
667 /*----- Signature generation ----------------------------------------------*/
669 static int sign(int argc
, char *argv
[])
676 const char *ki
= "dsig";
680 time_t exp
= KEXP_EXPIRE
;
682 const char *ifile
= 0;
683 const char *ofile
= 0;
692 static struct option opts
[] = {
693 { "null", 0, 0, '0' },
694 { "binary", 0, 0, 'b' },
695 { "verbose", 0, 0, 'v' },
696 { "quiet", 0, 0, 'q' },
697 { "comment", OPTF_ARGREQ
, 0, 'c' },
698 { "file", OPTF_ARGREQ
, 0, 'f' },
699 { "output", OPTF_ARGREQ
, 0, 'o' },
700 { "key", OPTF_ARGREQ
, 0, 'k' },
701 { "expire", OPTF_ARGREQ
, 0, 'e' },
704 int i
= mdwopt(argc
, argv
, "+0vqb" "c:" "f:o:" "k:e:", opts
, 0, 0, 0);
734 if (strcmp(optarg
, "forever") == 0)
736 else if ((exp
= get_date(optarg
, 0)) == -1)
737 die(EXIT_FAILURE
, "bad expiry time");
744 if (optind
!= argc
|| (f
& f_bogus
))
745 die(EXIT_FAILURE
, "Usage: sign [-OPTIONS]");
747 /* --- Locate the signing key --- */
749 if (key_open(&kf
, keyring
, KOPEN_WRITE
, keyreport
, 0))
750 die(EXIT_FAILURE
, "couldn't open keyring `%s'", keyring
);
751 if ((k
= key_bytag(&kf
, ki
)) == 0)
752 die(EXIT_FAILURE
, "couldn't find key `%s'", ki
);
754 if (exp
== KEXP_FOREVER
&& k
->exp
!= KEXP_FOREVER
) {
755 die(EXIT_FAILURE
, "key `%s' expires: can't create nonexpiring signature",
758 s
= getsig(k
, "dsig", 1);
760 /* --- Check the key --- */
762 if ((err
= s
->ops
->check(s
)) != 0)
763 moan("key `%s' fails check: %s", d
.buf
, err
);
765 /* --- Open files --- */
769 else if ((ifp
= fopen(ifile
, (f
& f_raw
) ?
"rb" : "r")) == 0) {
770 die(EXIT_FAILURE
, "couldn't open input file `%s': %s",
771 ifile
, strerror(errno
));
776 else if ((ofp
= fopen(ofile
, (f
& f_bin
) ?
"wb" : "w")) == 0) {
777 die(EXIT_FAILURE
, "couldn't open output file `%s': %s",
778 ofile
, strerror(errno
));
781 /* --- Emit the start of the output --- */
783 binit(&b
); b
.tag
= T_IDENT
;
784 dstr_putf(&b
.d
, "%s, Catacomb version " VERSION
, QUIS
);
785 bemit(&b
, ofp
, 0, f
& f_bin
);
787 breset(&b
); b
.tag
= T_KEYID
; b
.k
= k
->id
;
788 bemit(&b
, ofp
, 0, f
& f_bin
);
790 /* --- Start hashing, and emit the datestamps and things --- */
793 time_t now
= time(0);
795 breset(&b
); b
.tag
= T_DATE
; b
.t
= now
; bemit(&b
, ofp
, s
->h
, f
& f_bin
);
796 if (exp
== KEXP_EXPIRE
)
797 exp
= now
+ 86400 * 28;
798 breset(&b
); b
.tag
= T_EXPIRE
; b
.t
= exp
; bemit(&b
, ofp
, s
->h
, f
& f_bin
);
800 breset(&b
); b
.tag
= T_COMMENT
; DPUTS(&b
.d
, c
);
801 bemit(&b
, ofp
, s
->h
, f
& f_bin
);
808 /* --- Now hash the various files --- */
812 /* --- Stop on an output error --- */
819 /* --- Read the next filename to hash --- */
822 if (getstring(ifp
, &b
.d
, f
& f_raw
))
825 DENSURE(&b
.b
, GH_CLASS(s
->h
)->hashsz
);
826 if (fhash(GH_CLASS(s
->h
), b
.d
.buf
, b
.b
.buf
)) {
827 moan("Error reading `%s': %s", b
.d
.buf
, strerror(errno
));
830 b
.b
.len
+= GH_CLASS(s
->h
)->hashsz
;
832 fhex(stderr
, b
.b
.buf
, b
.b
.len
);
833 fprintf(stderr
, " %s\n", b
.d
.buf
);
835 bemit(&b
, ofp
, s
->h
, f
& f_bin
);
839 /* --- Create the signature --- */
841 if (!(f
& f_bogus
)) {
844 if ((e
= s
->ops
->doit(s
, &b
.b
)) != 0) {
845 moan("error creating signature: %s", key_strerror(e
));
848 if (!(f
& f_bogus
)) {
849 bemit(&b
, ofp
, 0, f
& f_bin
);
850 key_used(&kf
, k
, exp
);
854 /* --- Tidy up at the end --- */
867 if ((e
= key_close(&kf
)) != 0) {
870 die(EXIT_FAILURE
, "couldn't write file `%s': %s",
871 keyring
, strerror(errno
));
873 die(EXIT_FAILURE
, "keyring file `%s' broken: %s (repair manually)",
874 keyring
, strerror(errno
));
878 die(EXIT_FAILURE
, "error(s) occurred while creating signature");
879 return (EXIT_SUCCESS
);
886 /*----- Signature verification --------------------------------------------*/
888 static int verify(int argc
, char *argv
[])
905 /* --- Parse the options --- */
908 static struct option opts
[] = {
909 { "verbose", 0, 0, 'v' },
910 { "quiet", 0, 0, 'q' },
913 int i
= mdwopt(argc
, argv
, "+vq", opts
, 0, 0, 0);
931 if ((f
& f_bogus
) || argc
> 1)
932 die(EXIT_FAILURE
, "Usage: verify [-qv] [FILE]");
934 /* --- Open the key file, and start reading the input file --- */
936 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
937 die(EXIT_FAILURE
, "couldn't open keyring `%s'\n", keyring
);
941 if ((fp
= fopen(argv
[0], "rb")) == 0) {
942 die(EXIT_FAILURE
, "couldn't open file `%s': %s\n",
943 argv
[0], strerror(errno
));
950 if ((fp
= fopen(argv
[0], "r")) == 0) {
951 die(EXIT_FAILURE
, "couldn't open file `%s': %s\n",
952 argv
[0], strerror(errno
));
957 /* --- Read the introductory matter --- */
962 e
= bget(&b
, fp
, f
& f_bin
);
964 die(EXIT_FAILURE
, "error reading packet: %s", errtab
[-e
]);
970 printf("INFO ident: `%s'\n", b
.d
.buf
);
973 if ((k
= key_byid(&kf
, b
.k
)) == 0) {
975 printf("FAIL key %08lx not found\n", (unsigned long)b
.k
);
980 key_fulltag(k
, &b
.d
);
981 printf("INFO key: %s\n", b
.d
.buf
);
985 die(EXIT_FAILURE
, "(internal) unknown packet type\n");
990 /* --- Initialize the hash function and start reading hashed packets --- */
994 puts("FAIL no keyid packet found");
998 s
= getsig(k
, "dsig", 0);
999 if (verb
&& (err
= s
->ops
->check(s
)) != 0)
1000 printf("WARN public key fails check: %s", err
);
1006 printf("INFO comment: `%s'\n", b
.d
.buf
);
1007 bemit(&b
, 0, s
->h
, 0);
1012 timestring(b
.t
, &b
.d
);
1013 printf("INFO date: %s\n", b
.d
.buf
);
1015 bemit(&b
, 0, s
->h
, 0);
1018 time_t now
= time(0);
1019 if (b
.t
!= KEXP_FOREVER
&& b
.t
< now
) {
1021 puts("BAD signature has expired");
1026 timestring(b
.t
, &b
.d
);
1027 printf("INFO expires: %s\n", b
.d
.buf
);
1029 bemit(&b
, 0, s
->h
, 0);
1033 DENSURE(&d
, GH_CLASS(s
->h
)->hashsz
);
1034 if (fhash(GH_CLASS(s
->h
), b
.d
.buf
, d
.buf
)) {
1036 printf("BAD error reading file `%s': %s\n",
1037 b
.d
.buf
, strerror(errno
));
1040 } else if (b
.b
.len
!= GH_CLASS(s
->h
)->hashsz
||
1041 memcmp(d
.buf
, b
.b
.buf
, b
.b
.len
) != 0) {
1043 printf("BAD file `%s' has incorrect hash\n", b
.d
.buf
);
1045 } else if (verb
> 3) {
1046 fputs("INFO hash: ", stdout
);
1047 fhex(stdout
, b
.b
.buf
, b
.b
.len
);
1048 printf(" %s\n", b
.d
.buf
);
1050 bemit(&b
, 0, s
->h
, 0);
1053 if (s
->ops
->doit(s
, &b
.b
)) {
1055 puts("BAD bad signature");
1057 } else if (verb
> 2)
1058 puts("INFO good signature");
1062 printf("FAIL invalid packet type %i\n", e
);
1067 e
= bget(&b
, fp
, f
& f_bin
);
1070 printf("FAIL error reading packet: %s\n", errtab
[-e
]);
1083 puts("FAIL signature invalid");
1085 puts("OK signature verified");
1087 return (f
& f_bogus ? EXIT_FAILURE
: EXIT_SUCCESS
);
1094 /*----- Main code ---------------------------------------------------------*/
1098 listtab[i].name, listtab[i].name) \
1099 LI("Signature schemes", sig, \
1100 sigtab[i].name, sigtab[i].name) \
1101 LI("Hash functions", hash, \
1102 ghashtab[i], ghashtab[i]->name)
1104 MAKELISTTAB(listtab
, LISTS
)
1106 int cmd_show(int argc
, char *argv
[])
1108 return (displaylists(listtab
, argv
+ 1));
1111 static int cmd_help(int, char **);
1113 static cmd cmdtab
[] = {
1114 { "help", cmd_help
, "help [COMMAND...]" },
1115 { "show", cmd_show
, "show [ITEM...]" },
1117 "sign [-0bqv] [-c COMMENT] [-k TAG] [-e EXPIRE]\n\t\
1118 [-f FILE] [-o OUTPUT]",
1122 -0, --null Read null-terminated filenames from stdin.\n\
1123 -b, --binary Produce a binary output file.\n\
1124 -q, --quiet Produce fewer messages while working.\n\
1125 -v, --verbose Produce more messages while working.\n\
1126 -c, --comment=COMMENT Include COMMENT in the output file.\n\
1127 -f, --file=FILE Read filenames to hash from FILE.\n\
1128 -o, --output=FILE Write the signed result to FILE.\n\
1129 -k, --key=TAG Use a key named by TAG.\n\
1130 -e, --expire=TIME The signature should expire after TIME.\n\
1133 "verify [-qv] [FILE]", "\
1136 -q, --quiet Produce fewer messages while working.\n\
1137 -v, --verbose Produce more messages while working.\n\
1142 static int cmd_help(int argc
, char **argv
)
1144 sc_help(cmdtab
, stdout
, argv
+ 1);
1148 void version(FILE *fp
)
1150 pquis(fp
, "$, Catacomb version " VERSION
"\n");
1153 static void usage(FILE *fp
)
1155 pquis(fp
, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
1158 void help_global(FILE *fp
)
1162 Create and verify signatures on lists of files.\n\
1164 Global command-line options:\n\
1166 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
1167 -v, --version Show program version number.\n\
1168 -u, --usage Show a terse usage message.\n\
1170 -k, --keyring=FILE Read keys from FILE.\n",
1176 * Arguments: @int argc@ = number of command line arguments
1177 * @char *argv[]@ = vector of command line arguments
1179 * Returns: Zero if successful, nonzero otherwise.
1181 * Use: Signs or verifies signatures on lists of files. Useful for
1182 * ensuring that a distribution is unmolested.
1185 int main(int argc
, char *argv
[])
1191 /* --- Initialize the library --- */
1195 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
1196 rand_seed(RAND_GLOBAL
, 160);
1198 /* --- Parse options --- */
1201 static struct option opts
[] = {
1202 { "help", 0, 0, 'h' },
1203 { "version", 0, 0, 'v' },
1204 { "usage", 0, 0, 'u' },
1205 { "keyring", OPTF_ARGREQ
, 0, 'k' },
1208 int i
= mdwopt(argc
, argv
, "+hvu k:", opts
, 0, 0, 0);
1213 sc_help(cmdtab
, stdout
, argv
+ optind
);
1235 if (f
& f_bogus
|| argc
< 1) {
1240 /* --- Dispatch to the correct subcommand handler --- */
1242 return (findcmd(cmdtab
, argv
[0])->cmd(argc
, argv
));
1247 /*----- That's all, folks -------------------------------------------------*/