3 * $Id: dsig.c,v 1.12 2004/04/17 09:58:37 mdw Exp $
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 STORE32(d
->buf
+ d
->len
, ((b
->t
& ~MASK32
) >> 16) >> 16);
489 STORE32(d
->buf
+ d
->len
+ 4, b
->t
);
494 STORE32(d
->buf
+ d
->len
, b
->k
);
500 STORE16(d
->buf
+ d
->len
, b
->b
.len
);
503 if (b
->tag
== T_FILE
) {
511 /* --- @bwrite@ --- *
513 * Arguments: @block *b@ = pointer to block to write
514 * @FILE *fp@ = stream to write on
518 * Use: Writes a block on a stream in a textual format.
521 static void bwrite(block
*b
, FILE *fp
)
523 fputs(tagtab
[b
->tag
], fp
);
528 putstring(fp
, b
->d
.buf
, 0);
533 timestring(b
->t
, &d
);
534 putstring(fp
, d
.buf
, 0);
538 fprintf(fp
, "%08lx", (unsigned long)b
->k
);
546 base64_encode(&b64
, b
->b
.buf
, b
->b
.len
, &d
);
547 base64_encode(&b64
, 0, 0, &d
);
549 if (b
->tag
== T_FILE
) {
551 putstring(fp
, b
->d
.buf
, 0);
560 * Arguments: @block *b@ = pointer to block to write
561 * @FILE *fp@ = file to write on
562 * @ghash *h@ = pointer to hash function
563 * @unsigned bin@ = binary/text flag
567 * Use: Spits out a block properly.
570 static void bemit(block
*b
, FILE *fp
, ghash
*h
, unsigned bin
)
572 if (h
|| (fp
&& bin
)) {
576 GH_HASH(h
, d
.buf
, d
.len
);
578 fwrite(d
.buf
, d
.len
, 1, fp
);
584 /*----- Static variables --------------------------------------------------*/
586 static const char *keyring
= "keyring";
588 /*----- Other shared functions --------------------------------------------*/
590 /* --- @keyreport@ --- *
592 * Arguments: @const char *file@ = filename containing the error
593 * @int line@ = line number in file
594 * @const char *err@ = error text message
595 * @void *p@ = unimportant pointer
599 * Use: Reports errors during the opening of a key file.
602 static void keyreport(const char *file
, int line
, const char *err
, void *p
)
604 moan("error in keyring `%s' at line `%s': %s", file
, line
, err
);
609 * Arguments: @const gchash *c@ = pointer to hash class
610 * @const char *file@ = file to hash
611 * @void *b@ = pointer to output buffer
613 * Returns: Zero if it worked, or nonzero for a system error.
615 * Use: Hashes a file.
618 static int fhash(const gchash
*c
, const char *file
, void *b
)
620 FILE *fp
= fopen(file
, "rb");
621 ghash
*h
= GH_INIT(c
);
628 while ((sz
= fread(buf
, 1, sizeof(buf
), fp
)) > 0)
640 * Arguments: @FILE *fp@ = file to write on
641 * @const void *p@ = pointer to data to be written
642 * @size_t sz@ = size of the data to write
646 * Use: Emits a hex dump to a stream.
649 static void fhex(FILE *fp
, const void *p
, size_t sz
)
655 fprintf(fp
, "%02x", *q
++);
662 /*----- Signature generation ----------------------------------------------*/
664 static int sign(int argc
, char *argv
[])
671 const char *ki
= "dsig";
675 time_t exp
= KEXP_EXPIRE
;
677 const char *ifile
= 0;
678 const char *ofile
= 0;
687 static struct option opts
[] = {
688 { "null", 0, 0, '0' },
689 { "binary", 0, 0, 'b' },
690 { "verbose", 0, 0, 'v' },
691 { "quiet", 0, 0, 'q' },
692 { "comment", OPTF_ARGREQ
, 0, 'c' },
693 { "file", OPTF_ARGREQ
, 0, 'f' },
694 { "output", OPTF_ARGREQ
, 0, 'o' },
695 { "key", OPTF_ARGREQ
, 0, 'k' },
696 { "expire", OPTF_ARGREQ
, 0, 'e' },
699 int i
= mdwopt(argc
, argv
, "+0vqb" "c:" "f:o:" "k:e:", opts
, 0, 0, 0);
729 if (strcmp(optarg
, "forever") == 0)
731 else if ((exp
= get_date(optarg
, 0)) == -1)
732 die(EXIT_FAILURE
, "bad expiry time");
739 if (optind
!= argc
|| (f
& f_bogus
))
740 die(EXIT_FAILURE
, "Usage: sign [-options]");
742 /* --- Locate the signing key --- */
744 if (key_open(&kf
, keyring
, KOPEN_WRITE
, keyreport
, 0))
745 die(EXIT_FAILURE
, "couldn't open keyring `%s'", keyring
);
746 if ((k
= key_bytag(&kf
, ki
)) == 0)
747 die(EXIT_FAILURE
, "couldn't find key `%s'", ki
);
749 if (exp
== KEXP_FOREVER
&& k
->exp
!= KEXP_FOREVER
) {
750 die(EXIT_FAILURE
, "key `%s' expires: can't create nonexpiring signature",
753 s
= getsig(k
, "dsig", 1);
755 /* --- Check the key --- */
757 if ((err
= s
->ops
->check(s
)) != 0)
758 moan("key `%s' fails check: %s", d
.buf
, err
);
760 /* --- Open files --- */
764 else if ((ifp
= fopen(ifile
, (f
& f_raw
) ?
"rb" : "r")) == 0) {
765 die(EXIT_FAILURE
, "couldn't open input file `%s': %s",
766 ifile
, strerror(errno
));
771 else if ((ofp
= fopen(ofile
, (f
& f_bin
) ?
"wb" : "w")) == 0) {
772 die(EXIT_FAILURE
, "couldn't open output file `%s': %s",
773 ofile
, strerror(errno
));
776 /* --- Emit the start of the output --- */
778 binit(&b
); b
.tag
= T_IDENT
;
779 dstr_putf(&b
.d
, "%s, Catacomb version " VERSION
, QUIS
);
780 bemit(&b
, ofp
, 0, f
& f_bin
);
782 breset(&b
); b
.tag
= T_KEYID
; b
.k
= k
->id
;
783 bemit(&b
, ofp
, 0, f
& f_bin
);
785 /* --- Start hashing, and emit the datestamps and things --- */
788 time_t now
= time(0);
790 breset(&b
); b
.tag
= T_DATE
; b
.t
= now
; bemit(&b
, ofp
, s
->h
, f
& f_bin
);
791 if (exp
== KEXP_EXPIRE
)
792 exp
= now
+ 86400 * 28;
793 breset(&b
); b
.tag
= T_EXPIRE
; b
.t
= exp
; bemit(&b
, ofp
, s
->h
, f
& f_bin
);
795 breset(&b
); b
.tag
= T_COMMENT
; DPUTS(&b
.d
, c
);
796 bemit(&b
, ofp
, s
->h
, f
& f_bin
);
803 /* --- Now hash the various files --- */
807 /* --- Stop on an output error --- */
814 /* --- Read the next filename to hash --- */
817 if (getstring(ifp
, &b
.d
, f
& f_raw
))
820 DENSURE(&b
.b
, GH_CLASS(s
->h
)->hashsz
);
821 if (fhash(GH_CLASS(s
->h
), b
.d
.buf
, b
.b
.buf
)) {
822 moan("Error reading `%s': %s", b
.d
.buf
, strerror(errno
));
825 b
.b
.len
+= GH_CLASS(s
->h
)->hashsz
;
827 fhex(stderr
, b
.b
.buf
, b
.b
.len
);
828 fprintf(stderr
, " %s\n", b
.d
.buf
);
830 bemit(&b
, ofp
, s
->h
, f
& f_bin
);
834 /* --- Create the signature --- */
836 if (!(f
& f_bogus
)) {
839 if ((e
= s
->ops
->doit(s
, &b
.b
)) != 0) {
840 moan("error creating signature: %s", key_strerror(e
));
843 if (!(f
& f_bogus
)) {
844 bemit(&b
, ofp
, 0, f
& f_bin
);
845 key_used(&kf
, k
, exp
);
849 /* --- Tidy up at the end --- */
862 if ((e
= key_close(&kf
)) != 0) {
865 die(EXIT_FAILURE
, "couldn't write file `%s': %s",
866 keyring
, strerror(errno
));
868 die(EXIT_FAILURE
, "keyring file `%s' broken: %s (repair manually)",
869 keyring
, strerror(errno
));
873 die(EXIT_FAILURE
, "error(s) occurred while creating signature");
874 return (EXIT_SUCCESS
);
881 /*----- Signature verification --------------------------------------------*/
883 static int verify(int argc
, char *argv
[])
900 /* --- Parse the options --- */
903 static struct option opts
[] = {
904 { "verbose", 0, 0, 'v' },
905 { "quiet", 0, 0, 'q' },
908 int i
= mdwopt(argc
, argv
, "+vq", opts
, 0, 0, 0);
926 if ((f
& f_bogus
) || argc
> 1)
927 die(EXIT_FAILURE
, "Usage: verify [-qv] [file]");
929 /* --- Open the key file, and start reading the input file --- */
931 if (key_open(&kf
, keyring
, KOPEN_READ
, keyreport
, 0))
932 die(EXIT_FAILURE
, "couldn't open keyring `%s'\n", keyring
);
936 if ((fp
= fopen(argv
[0], "rb")) == 0) {
937 die(EXIT_FAILURE
, "couldn't open file `%s': %s\n",
938 argv
[0], strerror(errno
));
945 if ((fp
= fopen(argv
[0], "r")) == 0) {
946 die(EXIT_FAILURE
, "couldn't open file `%s': %s\n",
947 argv
[0], strerror(errno
));
952 /* --- Read the introductory matter --- */
957 e
= bget(&b
, fp
, f
& f_bin
);
959 die(EXIT_FAILURE
, "error reading packet: %s", errtab
[-e
]);
965 printf("INFO ident: `%s'\n", b
.d
.buf
);
968 if ((k
= key_byid(&kf
, b
.k
)) == 0) {
970 printf("FAIL key %08lx not found\n", (unsigned long)b
.k
);
975 key_fulltag(k
, &b
.d
);
976 printf("INFO key: %s\n", b
.d
.buf
);
980 die(EXIT_FAILURE
, "(internal) unknown packet type\n");
985 /* --- Initialize the hash function and start reading hashed packets --- */
989 puts("FAIL no keyid packet found");
993 s
= getsig(k
, "dsig", 0);
994 if (verb
&& (err
= s
->ops
->check(s
)) != 0)
995 printf("WARN public key fails check: %s", err
);
1001 printf("INFO comment: `%s'\n", b
.d
.buf
);
1002 bemit(&b
, 0, s
->h
, 0);
1007 timestring(b
.t
, &b
.d
);
1008 printf("INFO date: %s\n", b
.d
.buf
);
1010 bemit(&b
, 0, s
->h
, 0);
1013 time_t now
= time(0);
1016 puts("BAD signature has expired");
1021 timestring(b
.t
, &b
.d
);
1022 printf("INFO expires: %s\n", b
.d
.buf
);
1024 bemit(&b
, 0, s
->h
, 0);
1028 DENSURE(&d
, GH_CLASS(s
->h
)->hashsz
);
1029 if (fhash(GH_CLASS(s
->h
), b
.d
.buf
, d
.buf
)) {
1031 printf("BAD error reading file `%s': %s\n",
1032 b
.d
.buf
, strerror(errno
));
1035 } else if (b
.b
.len
!= GH_CLASS(s
->h
)->hashsz
||
1036 memcmp(d
.buf
, b
.b
.buf
, b
.b
.len
) != 0) {
1038 printf("BAD file `%s' has incorrect hash\n", b
.d
.buf
);
1040 } else if (verb
> 3) {
1041 fputs("INFO hash: ", stdout
);
1042 fhex(stdout
, b
.b
.buf
, b
.b
.len
);
1043 printf(" %s\n", b
.d
.buf
);
1045 bemit(&b
, 0, s
->h
, 0);
1048 if (s
->ops
->doit(s
, &b
.b
)) {
1050 puts("BAD bad signature");
1052 } else if (verb
> 2)
1053 puts("INFO good signature");
1057 printf("FAIL invalid packet type %i\n", e
);
1062 e
= bget(&b
, fp
, f
& f_bin
);
1065 printf("FAIL error reading packet: %s\n", errtab
[-e
]);
1078 puts("FAIL signature invalid");
1080 puts("OK signature verified");
1082 return (f
& f_bogus ? EXIT_FAILURE
: EXIT_SUCCESS
);
1089 /*----- Main code ---------------------------------------------------------*/
1091 typedef struct cmd
{
1093 int (*func
)(int /*argc*/, char */
*argv*/
[]);
1098 static cmd cmdtab
[] = {
1100 "sign [-0bqv] [-c comment] [-k tag] [-e expire] [-f file] [-o output]",
1104 -0, --null Read null-terminated filenames from stdin.\n\
1105 -b, --binary Produce a binary output file.\n\
1106 -q, --quiet Produce fewer messages while working.\n\
1107 -v, --verbose Produce more messages while working.\n\
1108 -c, --comment=COMMENT Include COMMENT in the output file.\n\
1109 -f, --file=FILE Read filenames to hash from FILE.\n\
1110 -o, --output=FILE Write the signed result to FILE.\n\
1111 -k, --key=TAG Use a key named by TAG.\n\
1112 -e, --expire=TIME The signature should expire after TIME.\n\
1115 "verify [-qv] [file]", "\
1118 -q, --quiet Produce fewer messages while working.\n\
1119 -v, --verbose Produce more messages while working.\n\
1124 /* --- @findcmd@ --- *
1126 * Arguments: @const char *name@ = a command name
1128 * Returns: Pointer to the command structure.
1130 * Use: Looks up a command by name. If the command isn't found, an
1131 * error is reported and the program is terminated.
1134 static cmd
*findcmd(const char *name
)
1136 cmd
*c
, *chosen
= 0;
1137 size_t sz
= strlen(name
);
1139 for (c
= cmdtab
; c
->name
; c
++) {
1140 if (strncmp(name
, c
->name
, sz
) == 0) {
1141 if (c
->name
[sz
] == 0) {
1145 die(EXIT_FAILURE
, "ambiguous command name `%s'", name
);
1151 die(EXIT_FAILURE
, "unknown command name `%s'", name
);
1155 static void version(FILE *fp
)
1157 pquis(fp
, "$, Catacomb version " VERSION
"\n");
1160 static void usage(FILE *fp
)
1162 pquis(fp
, "Usage: $ [-k keyring] command [args]\n");
1165 static void help(FILE *fp
, char **argv
)
1171 fprintf(fp
, "Usage: %s [-k keyring] %s\n", QUIS
, c
->usage
);
1181 Create and verify signatures on lists of files.\n\
1183 for (c
= cmdtab
; c
->name
; c
++)
1184 fprintf(fp
, "%s\n", c
->usage
);
1190 * Arguments: @int argc@ = number of command line arguments
1191 * @char *argv[]@ = vector of command line arguments
1193 * Returns: Zero if successful, nonzero otherwise.
1195 * Use: Signs or verifies signatures on lists of files. Useful for
1196 * ensuring that a distribution is unmolested.
1199 int main(int argc
, char *argv
[])
1205 /* --- Initialize the library --- */
1209 rand_noisesrc(RAND_GLOBAL
, &noise_source
);
1210 rand_seed(RAND_GLOBAL
, 160);
1212 /* --- Parse options --- */
1215 static struct option opts
[] = {
1216 { "help", 0, 0, 'h' },
1217 { "version", 0, 0, 'v' },
1218 { "usage", 0, 0, 'u' },
1219 { "keyring", OPTF_ARGREQ
, 0, 'k' },
1222 int i
= mdwopt(argc
, argv
, "+hvu k:", opts
, 0, 0, 0);
1227 help(stdout
, argv
+ optind
);
1249 if (f
& f_bogus
|| argc
< 1) {
1254 /* --- Dispatch to the correct subcommand handler --- */
1256 return (findcmd(argv
[0])->func(argc
, argv
));
1261 /*----- That's all, folks -------------------------------------------------*/