chiark / gitweb /
Merge branch '2.4.x' into 2.5.x
[catacomb] / progs / dsig.c
1 /* -*-c-*-
2  *
3  * Verify signatures on distribuitions of files
4  *
5  * (c) 2000 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Catacomb.
11  *
12  * Catacomb is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * Catacomb is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with Catacomb; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #define _FILE_OFFSET_BITS 64
31
32 #include "config.h"
33
34 #include <ctype.h>
35 #include <errno.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
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>
45 #include <mLib/sub.h>
46
47 #include "getdate.h"
48 #include "rand.h"
49 #include "ghash.h"
50 #include "key.h"
51 #include "key-data.h"
52 #include "noise.h"
53 #include "cc.h"
54
55 /*----- Data formatting ---------------------------------------------------*/
56
57 /* --- Binary data structure --- *
58  *
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.
62  */
63
64 enum {
65   /* --- Block tags --- */
66
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 */
75
76   /* --- Error messages --- */
77
78   E_EOF = -1,
79   E_BIN = -2,
80   E_TAG = -3,
81   E_DATE = -4
82 };
83
84 /* --- Name translation table --- */
85
86 static const char *tagtab[] = {
87   "ident:", "keyid:",
88   "comment:", "date:", "expires:", "file:",
89   "signature:",
90   0
91 };
92
93 static const char *errtab[] = {
94   "Off-by-one bug",
95   "Unexpected end-of-file",
96   "Binary object too large",
97   "Unrecognized tag",
98   "Bad date string"
99 };
100
101 /* --- Memory representation of block types --- */
102
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 */
109 } block;
110
111 /* --- @timestring@ --- *
112  *
113  * Arguments:   @time_t t@ = a timestamp
114  *              @dstr *d@ = a string to write on
115  *
116  * Returns:     ---
117  *
118  * Use:         Writes a textual representation of the timestamp to the
119  *              string.
120  */
121
122 static void timestring(time_t t, dstr *d)
123 {
124   if (t == KEXP_FOREVER)
125     DPUTS(d, "forever");
126   else {
127     struct tm *tm = localtime(&t);
128     DENSURE(d, 32);
129     d->len += strftime(d->buf + d->len, 32, "%Y-%m-%d %H:%M:%S %Z", tm);
130     DPUTZ(d);
131   }
132 }
133
134 /* --- @breset@ --- *
135  *
136  * Arguments:   @block *b@ = block to reset
137  *
138  * Returns:     ---
139  *
140  * Use:         Resets a block so that more stuff can be put in it.
141  */
142
143 static void breset(block *b)
144 {
145   b->tag = 0;
146   DRESET(&b->d);
147   DRESET(&b->b);
148   b->k = 0;
149   b->t = KEXP_EXPIRE;
150 }
151
152 /* --- @binit@ --- *
153  *
154  * Arguments:   @block *b@ = block to initialize
155  *
156  * Returns:     ---
157  *
158  * Use:         Initializes a block as something to read into.
159  */
160
161 static void binit(block *b)
162 {
163   dstr_create(&b->d);
164   dstr_create(&b->b);
165   breset(b);
166 }
167
168 /* --- @bdestroy@ --- *
169  *
170  * Arguments:   @block *b@ = block to destroy
171  *
172  * Returns:     ---
173  *
174  * Use:         Destroys a block's contents.
175  */
176
177 static void bdestroy(block *b)
178 {
179   dstr_destroy(&b->d);
180   dstr_destroy(&b->b);
181 }
182
183 /* --- @bget@ --- *
184  *
185  * Arguments:   @block *b@ = pointer to block
186  *              @FILE *fp@ = stream to read from
187  *              @unsigned bin@ = binary switch
188  *
189  * Returns:     Tag of block, or an error tag.
190  *
191  * Use:         Reads a block from a stream.
192  */
193
194 static int bget(block *b, FILE *fp, unsigned bin)
195 {
196   int tag;
197
198   /* --- Read the tag --- */
199
200   if (bin)
201     tag = getc(fp);
202   else {
203     dstr d = DSTR_INIT;
204     if (getstring(fp, &d, GSF_FILE))
205       return (E_EOF);
206     for (tag = 0; tagtab[tag]; tag++) {
207       if (strcmp(tagtab[tag], d.buf) == 0)
208         goto done;
209     }
210     return (E_TAG);
211   done:;
212   }
213
214   /* --- Decide what to do next --- */
215
216   breset(b);
217   b->tag = tag;
218   switch (tag) {
219
220     /* --- Reading of strings --- */
221
222     case T_IDENT:
223     case T_COMMENT:
224       if (getstring(fp, &b->d, GSF_FILE | (bin ? GSF_RAW : 0)))
225         return (E_EOF);
226       break;
227
228     /* --- Timestamps --- */
229
230     case T_DATE:
231     case T_EXPIRE:
232       if (bin) {
233         octet buf[8];
234         if (fread(buf, sizeof(buf), 1, fp) < 1)
235           return (E_EOF);
236         b->t = ((time_t)(((LOAD32(buf + 0) << 16) << 16) &
237                          ~(unsigned long)MASK32) |
238                 (time_t)LOAD32(buf + 4));
239       } else {
240         if (getstring(fp, &b->d, GSF_FILE))
241           return (E_EOF);
242         if (strcmp(b->d.buf, "forever") == 0)
243           b->t = KEXP_FOREVER;
244         else if ((b->t = get_date(b->d.buf, 0)) == -1)
245           return (E_DATE);
246       }
247       break;
248
249     /* --- Key ids --- */
250
251     case T_KEYID:
252       if (bin) {
253         octet buf[4];
254         if (fread(buf, sizeof(buf), 1, fp) < 1)
255           return (E_EOF);
256         b->k = LOAD32(buf);
257       } else {
258         if (getstring(fp, &b->d, GSF_FILE))
259           return (E_EOF);
260         b->k = strtoul(b->d.buf, 0, 16);
261       }
262       break;
263
264     /* --- Reading of binary data --- */
265
266     case T_FILE:
267     case T_SIGNATURE:
268       if (bin) {
269         octet buf[2];
270         uint32 sz;
271         if (fread(buf, sizeof(buf), 1, fp) < 1)
272           return (E_EOF);
273         sz = LOAD16(buf);
274         if (sz > 4096)
275           return (E_BIN);
276         DENSURE(&b->b, sz);
277         if (fread(b->b.buf + b->b.len, 1, sz, fp) < sz)
278           return (E_EOF);
279         b->b.len += sz;
280       } else {
281         base64_ctx b64;
282         if (getstring(fp, &b->d, GSF_FILE))
283           return (E_EOF);
284         base64_init(&b64);
285         base64_decode(&b64, b->d.buf, b->d.len, &b->b);
286         base64_decode(&b64, 0, 0, &b->b);
287         DRESET(&b->d);
288       }
289       if (tag == T_FILE &&
290           getstring(fp, &b->d, GSF_FILE | (bin ? GSF_RAW : 0)))
291         return (E_EOF);
292       break;
293
294       /* --- Anything else --- */
295
296     default:
297       return (E_TAG);
298   }
299
300   return (tag);
301 }
302
303 /* --- @blob@ --- *
304  *
305  * Arguments:   @block *b@ = pointer to block to emit
306  *              @dstr *d@ = output buffer
307  *
308  * Returns:     ---
309  *
310  * Use:         Encodes a block in a binary format.
311  */
312
313 static void blob(block *b, dstr *d)
314 {
315   DPUTC(d, b->tag);
316   switch (b->tag) {
317     case T_IDENT:
318     case T_COMMENT:
319       DPUTD(d, &b->d);
320       DPUTC(d, 0);
321       break;
322     case T_DATE:
323     case T_EXPIRE:
324       DENSURE(d, 8);
325       if (b->t == KEXP_FOREVER) {
326         STORE32(d->buf + d->len, 0xffffffff);
327         STORE32(d->buf + d->len + 4, 0xffffffff);
328       } else {
329         STORE32(d->buf + d->len,
330                 ((b->t & ~(unsigned long)MASK32) >> 16) >> 16);
331         STORE32(d->buf + d->len + 4, b->t);
332       }
333       d->len += 8;
334       break;
335     case T_KEYID:
336       DENSURE(d, 4);
337       STORE32(d->buf + d->len, b->k);
338       d->len += 4;
339       break;
340     case T_FILE:
341     case T_SIGNATURE:
342       DENSURE(d, 2);
343       STORE16(d->buf + d->len, b->b.len);
344       d->len += 2;
345       DPUTD(d, &b->b);
346       if (b->tag == T_FILE) {
347         DPUTD(d, &b->d);
348         DPUTC(d, 0);
349       }
350       break;
351   }
352 }
353
354 /* --- @bwrite@ --- *
355  *
356  * Arguments:   @block *b@ = pointer to block to write
357  *              @FILE *fp@ = stream to write on
358  *
359  * Returns:     ---
360  *
361  * Use:         Writes a block on a stream in a textual format.
362  */
363
364 static void bwrite(block *b, FILE *fp)
365 {
366   fputs(tagtab[b->tag], fp);
367   putc(' ', fp);
368   switch (b->tag) {
369     case T_IDENT:
370     case T_COMMENT:
371       putstring(fp, b->d.buf, 0);
372       break;
373     case T_DATE:
374     case T_EXPIRE: {
375       dstr d = DSTR_INIT;
376       timestring(b->t, &d);
377       putstring(fp, d.buf, 0);
378       dstr_destroy(&d);
379     } break;
380     case T_KEYID:
381       fprintf(fp, "%08lx", (unsigned long)b->k);
382       break;
383     case T_FILE:
384     case T_SIGNATURE: {
385       dstr d = DSTR_INIT;
386       base64_ctx b64;
387       base64_init(&b64);
388       b64.maxline = 0;
389       base64_encode(&b64, b->b.buf, b->b.len, &d);
390       base64_encode(&b64, 0, 0, &d);
391       dstr_write(&d, fp);
392       if (b->tag == T_FILE) {
393         putc(' ', fp);
394         putstring(fp, b->d.buf, 0);
395       }
396     } break;
397   }
398   putc('\n', fp);
399 }
400
401 /* --- @bemit@ --- *
402  *
403  * Arguments:   @block *b@ = pointer to block to write
404  *              @FILE *fp@ = file to write on
405  *              @ghash *h@ = pointer to hash function
406  *              @unsigned bin@ = binary/text flag
407  *
408  * Returns:     ---
409  *
410  * Use:         Spits out a block properly.
411  */
412
413 static void bemit(block *b, FILE *fp, ghash *h, unsigned bin)
414 {
415   if (h || (fp && bin)) {
416     dstr d = DSTR_INIT;
417     blob(b, &d);
418     if (h)
419       GH_HASH(h, d.buf, d.len);
420     if (fp && bin)
421       fwrite(d.buf, d.len, 1, fp);
422   }
423   if (fp && !bin)
424     bwrite(b, fp);
425 }
426
427 /*----- Static variables --------------------------------------------------*/
428
429 static const char *keyring = "keyring";
430
431 /*----- Other shared functions --------------------------------------------*/
432
433 /* --- @fhex@ --- *
434  *
435  * Arguments:   @FILE *fp@ = file to write on
436  *              @const void *p@ = pointer to data to be written
437  *              @size_t sz@ = size of the data to write
438  *
439  * Returns:     ---
440  *
441  * Use:         Emits a hex dump to a stream.
442  */
443
444 static void fhex(FILE *fp, const void *p, size_t sz)
445 {
446   const octet *q = p;
447   if (!sz)
448     return;
449   for (;;) {
450     fprintf(fp, "%02x", *q++);
451     sz--;
452     if (!sz)
453       break;
454   }
455 }
456
457 /*----- Signature generation ----------------------------------------------*/
458
459 static int sign(int argc, char *argv[])
460 {
461 #define f_bogus 1u
462 #define f_bin 2u
463 #define f_nocheck 4u
464
465   unsigned f = 0;
466   const char *ki = "dsig";
467   key_file kf;
468   key *k;
469   sig *s;
470   fhashstate fh;
471   time_t exp = KEXP_EXPIRE;
472   unsigned verb = 0;
473   const char *ifile = 0, *hfile = 0;
474   const char *ofile = 0;
475   const char *c = 0;
476   const char *err;
477   FILE *ifp, *ofp;
478   dstr d = DSTR_INIT;
479   hfpctx hfp;
480   block b;
481   int e, hf, n;
482
483   for (;;) {
484     static struct option opts[] = {
485       { "null",         0,              0,      '0' },
486       { "binary",       0,              0,      'b' },
487       { "verbose",      0,              0,      'v' },
488       { "progress",     0,              0,      'p' },
489       { "quiet",        0,              0,      'q' },
490       { "comment",      OPTF_ARGREQ,    0,      'c' },
491       { "file",         OPTF_ARGREQ,    0,      'f' },
492       { "hashes",       OPTF_ARGREQ,    0,      'h' },
493       { "output",       OPTF_ARGREQ,    0,      'o' },
494       { "key",          OPTF_ARGREQ,    0,      'k' },
495       { "expire",       OPTF_ARGREQ,    0,      'e' },
496       { "nocheck",      OPTF_ARGREQ,    0,      'C' },
497       { 0,              0,              0,      0 }
498     };
499     int i = mdwopt(argc, argv, "+0vpqbC" "c:" "f:h:o:" "k:e:",
500                    opts, 0, 0, 0);
501     if (i < 0)
502       break;
503     switch (i) {
504       case '0':
505         f |= GSF_RAW;
506         break;
507       case 'b':
508         f |= f_bin;
509         break;
510       case 'v':
511         verb++;
512         break;
513       case 'p':
514         f |= FHF_PROGRESS;
515         break;
516       case 'q':
517         if (verb > 0)
518           verb--;
519         break;
520       case 'C':
521         f |= f_nocheck;
522         break;
523       case 'c':
524         c = optarg;
525         break;
526       case 'f':
527         ifile = optarg;
528         break;
529       case 'h':
530         hfile = optarg;
531         break;
532       case 'o':
533         ofile = optarg;
534         break;
535       case 'k':
536         ki = optarg;
537         break;
538       case 'e':
539         if (strcmp(optarg, "forever") == 0)
540           exp = KEXP_FOREVER;
541         else if ((exp = get_date(optarg, 0)) == -1)
542           die(EXIT_FAILURE, "bad expiry time");
543         break;
544       default:
545         f |= f_bogus;
546         break;
547     }
548   }
549   if (optind != argc || (f & f_bogus))
550     die(EXIT_FAILURE, "Usage: sign [-OPTIONS]");
551   if (hfile && ifile)
552     die(EXIT_FAILURE, "Inconsistent options `-h' and `-f'");
553
554   /* --- Locate the signing key --- */
555
556   if (key_open(&kf, keyring, KOPEN_WRITE, key_moan, 0))
557     die(EXIT_FAILURE, "couldn't open keyring `%s'", keyring);
558   if ((k = key_bytag(&kf, ki)) == 0)
559     die(EXIT_FAILURE, "couldn't find key `%s'", ki);
560   key_fulltag(k, &d);
561   if (exp == KEXP_FOREVER && k->exp != KEXP_FOREVER) {
562     die(EXIT_FAILURE, "key `%s' expires: can't create nonexpiring signature",
563         d.buf);
564   }
565   s = getsig(k, "dsig", 1);
566
567   /* --- Check the key --- */
568
569   if (!(f & f_nocheck) && (err = s->ops->check(s)) != 0)
570     moan("key `%s' fails check: %s", d.buf, err);
571
572   /* --- Open files --- */
573
574   if (hfile) ifile = hfile;
575   if (!ifile || strcmp(ifile, "-") == 0)
576     ifp = stdin;
577   else if ((ifp = fopen(ifile, (f & f_bin) ? "rb" : "r")) == 0) {
578     die(EXIT_FAILURE, "couldn't open input file `%s': %s",
579         ifile, strerror(errno));
580   }
581
582   if (!ofile || strcmp(ofile, "-") == 0)
583     ofp = stdout;
584   else if ((ofp = fopen(ofile, (f & f_bin) ? "wb" : "w")) == 0) {
585     die(EXIT_FAILURE, "couldn't open output file `%s': %s",
586         ofile, strerror(errno));
587   }
588
589   /* --- Emit the start of the output --- */
590
591   binit(&b); b.tag = T_IDENT;
592   dstr_putf(&b.d, "%s, Catacomb version " VERSION, QUIS);
593   bemit(&b, ofp, 0, f & f_bin);
594
595   breset(&b); b.tag = T_KEYID; b.k = k->id;
596   bemit(&b, ofp, 0, f & f_bin);
597
598   /* --- Start hashing, and emit the datestamps and things --- */
599
600   {
601     time_t now = time(0);
602
603     breset(&b); b.tag = T_DATE; b.t = now; bemit(&b, ofp, s->h, f & f_bin);
604     if (exp == KEXP_EXPIRE)
605       exp = now + 86400 * 28;
606     breset(&b); b.tag = T_EXPIRE; b.t = exp; bemit(&b, ofp, s->h, f & f_bin);
607     if (c) {
608       breset(&b); b.tag = T_COMMENT; DPUTS(&b.d, c);
609       bemit(&b, ofp, s->h, f & f_bin);
610     }
611
612     if (!(f & f_bin))
613       putc('\n', ofp);
614   }
615
616   /* --- Now hash the various files --- */
617
618   if (hfile) {
619     hfp.f = f;
620     hfp.fp = ifp;
621     hfp.ee = &encodingtab[ENC_HEX];
622     hfp.gch = GH_CLASS(s->h);
623     hfp.dline = &d;
624     hfp.dfile = &b.d;
625
626     n = 0;
627     for (;;) {
628       breset(&b);
629       DENSURE(&b.b, hfp.gch->hashsz);
630       hfp.hbuf = (octet *)b.b.buf;
631       if (ferror(ofp)) { f |= f_bogus; break; }
632       if ((hf = hfparse(&hfp)) == HF_EOF) break;
633       n++;
634
635       switch (hf) {
636         case HF_HASH:
637           if (hfp.gch != GH_CLASS(s->h)) {
638             moan("%s:%d: incorrect hash function `%s' (should be `%s')",
639                  hfile, n, hfp.gch->name, GH_CLASS(s->h)->name);
640             f |= f_bogus;
641           }
642           break;
643         case HF_BAD:
644           moan("%s:%d: invalid hash-file line", hfile, n);
645           f |= f_bogus;
646           break;
647         case HF_FILE:
648           b.tag = T_FILE;
649           b.b.len += hfp.gch->hashsz;
650           bemit(&b, ofp, s->h, f & f_bin);
651           break;
652       }
653     }
654   } else {
655     for (;;) {
656
657       /* --- Stop on an output error --- */
658
659       if (ferror(ofp)) {
660         f |= f_bogus;
661         break;
662       }
663
664       /* --- Read the next filename to hash --- */
665
666       fhash_init(&fh, GH_CLASS(s->h), f | FHF_BINARY);
667       breset(&b);
668       if (getstring(ifp, &b.d, GSF_FILE | f))
669         break;
670       b.tag = T_FILE;
671       DENSURE(&b.b, GH_CLASS(s->h)->hashsz);
672       if (fhash(&fh, b.d.buf, b.b.buf)) {
673         moan("error reading `%s': %s", b.d.buf, strerror(errno));
674         f |= f_bogus;
675       } else {
676         b.b.len += GH_CLASS(s->h)->hashsz;
677         if (verb) {
678           fhex(stderr, b.b.buf, b.b.len);
679           fprintf(stderr, " %s\n", b.d.buf);
680         }
681         bemit(&b, ofp, s->h, f & f_bin);
682       }
683       fhash_free(&fh);
684     }
685   }
686
687   /* --- Create the signature --- */
688
689   if (!(f & f_bogus)) {
690     breset(&b);
691     b.tag = T_SIGNATURE;
692     if ((e = s->ops->doit(s, &b.b)) != 0) {
693       moan("error creating signature: %s", key_strerror(e));
694       f |= f_bogus;
695     }
696     if (!(f & f_bogus)) {
697       bemit(&b, ofp, 0, f & f_bin);
698       key_used(&kf, k, exp);
699     }
700   }
701
702   /* --- Tidy up at the end --- */
703
704   freesig(s);
705   bdestroy(&b);
706   if (ifile)
707     fclose(ifp);
708   if (ofile) {
709     if (fclose(ofp))
710       f |= f_bogus;
711   } else {
712     if (fflush(ofp))
713       f |= f_bogus;
714   }
715   if ((e = key_close(&kf)) != 0) {
716     switch (e) {
717       case KWRITE_FAIL:
718         die(EXIT_FAILURE, "couldn't write file `%s': %s",
719             keyring, strerror(errno));
720       case KWRITE_BROKEN:
721         die(EXIT_FAILURE, "keyring file `%s' broken: %s (repair manually)",
722             keyring, strerror(errno));
723     }
724   }
725   if (f & f_bogus)
726     die(EXIT_FAILURE, "error(s) occurred while creating signature");
727   return (EXIT_SUCCESS);
728
729 #undef f_bin
730 #undef f_bogus
731 #undef f_nocheck
732 }
733
734 /*----- Signature verification --------------------------------------------*/
735
736 static int checkjunk(const char *path, const struct stat *st, void *p)
737 {
738   if (!st) printf("JUNK (error %s) %s\n", strerror(errno), path);
739   else printf("JUNK %s %s\n", describefile(st), path);
740   return (0);
741 }
742
743 static int verify(int argc, char *argv[])
744 {
745 #define f_bogus 1u
746 #define f_bin 2u
747 #define f_ok 4u
748 #define f_nocheck 8u
749
750   unsigned f = 0;
751   unsigned verb = 1;
752   key_file kf;
753   key *k = 0;
754   sig *s;
755   dstr d = DSTR_INIT;
756   const char *err;
757   fhashstate fh;
758   FILE *fp;
759   block b;
760   int e;
761
762   /* --- Parse the options --- */
763
764   for (;;) {
765     static struct option opts[] = {
766       { "verbose",      0,              0,      'v' },
767       { "progress",     0,              0,      'p' },
768       { "quiet",        0,              0,      'q' },
769       { "nocheck",      0,              0,      'C' },
770       { "junk",         0,              0,      'j' },
771       { 0,              0,              0,      0 }
772     };
773     int i = mdwopt(argc, argv, "+vpqCj", opts, 0, 0, 0);
774     if (i < 0)
775       break;
776     switch (i) {
777       case 'v':
778         verb++;
779         break;
780       case 'p':
781         f |= FHF_PROGRESS;
782         break;
783       case 'q':
784         if (verb)
785           verb--;
786         break;
787       case 'C':
788         f |= f_nocheck;
789         break;
790       case 'j':
791         f |= FHF_JUNK;
792         break;
793       default:
794         f |= f_bogus;
795         break;
796     }
797   }
798   argc -= optind;
799   argv += optind;
800   if ((f & f_bogus) || argc > 1)
801     die(EXIT_FAILURE, "Usage: verify [-qvC] [FILE]");
802
803   /* --- Open the key file, and start reading the input file --- */
804
805   if (key_open(&kf, keyring, KOPEN_READ, key_moan, 0))
806     die(EXIT_FAILURE, "couldn't open keyring `%s'\n", keyring);
807   if (argc < 1)
808     fp = stdin;
809   else {
810     if ((fp = fopen(argv[0], "rb")) == 0) {
811       die(EXIT_FAILURE, "couldn't open file `%s': %s\n",
812               argv[0], strerror(errno));
813     }
814     if (getc(fp) == 0) {
815       ungetc(0, fp);
816       f |= f_bin;
817     } else {
818       fclose(fp);
819       if ((fp = fopen(argv[0], "r")) == 0) {
820         die(EXIT_FAILURE, "couldn't open file `%s': %s\n",
821                 argv[0], strerror(errno));
822       }
823     }
824   }
825
826   /* --- Read the introductory matter --- */
827
828   binit(&b);
829   for (;;) {
830     breset(&b);
831     e = bget(&b, fp, f & f_bin);
832     if (e < 0)
833       die(EXIT_FAILURE, "error reading packet: %s", errtab[-e]);
834     if (e >= T_BEGIN)
835       break;
836     switch (e) {
837       case T_IDENT:
838         if (verb > 2)
839           printf("INFO ident: `%s'\n", b.d.buf);
840         break;
841       case T_KEYID:
842         if ((k = key_byid(&kf, b.k)) == 0) {
843           if (verb)
844             printf("FAIL key %08lx not found\n", (unsigned long)b.k);
845           exit(EXIT_FAILURE);
846         }
847         if (verb > 2) {
848           DRESET(&b.d);
849           key_fulltag(k, &b.d);
850           printf("INFO key: %s\n", b.d.buf);
851         }
852         break;
853       default:
854         die(EXIT_FAILURE, "(internal) unknown packet type\n");
855         break;
856     }
857   }
858
859   /* --- Initialize the hash function and start reading hashed packets --- */
860
861   if (!k) {
862     if (verb)
863       puts("FAIL no keyid packet found");
864     exit(EXIT_FAILURE);
865   }
866
867   s = getsig(k, "dsig", 0);
868   if (!(f & f_nocheck) && verb && (err = s->ops->check(s)) != 0)
869     printf("WARN public key fails check: %s", err);
870
871   fhash_init(&fh, GH_CLASS(s->h), f | FHF_BINARY);
872   for (;;) {
873     switch (e) {
874       case T_COMMENT:
875         if (verb > 1)
876           printf("INFO comment: `%s'\n", b.d.buf);
877         bemit(&b, 0, s->h, 0);
878         break;
879       case T_DATE:
880         if (verb > 2) {
881           DRESET(&b.d);
882           timestring(b.t, &b.d);
883           printf("INFO date: %s\n", b.d.buf);
884         }
885         bemit(&b, 0, s->h, 0);
886         break;
887       case T_EXPIRE: {
888         time_t now = time(0);
889         if (b.t != KEXP_FOREVER && b.t < now) {
890           if (verb > 1)
891             puts("BAD signature has expired");
892           f |= f_bogus;
893         }
894         if (verb > 2) {
895           DRESET(&b.d);
896           timestring(b.t, &b.d);
897           printf("INFO expires: %s\n", b.d.buf);
898         }
899         bemit(&b, 0, s->h, 0);
900       } break;
901       case T_FILE:
902         DRESET(&d);
903         DENSURE(&d, GH_CLASS(s->h)->hashsz);
904         if (fhash(&fh, b.d.buf, d.buf)) {
905           if (verb > 1) {
906             printf("BAD error reading file `%s': %s\n",
907                     b.d.buf, strerror(errno));
908           }
909           f |= f_bogus;
910         } else if (b.b.len != GH_CLASS(s->h)->hashsz ||
911                    memcmp(d.buf, b.b.buf, b.b.len) != 0) {
912           if (verb > 1)
913             printf("BAD file `%s' has incorrect hash\n", b.d.buf);
914           f |= f_bogus;
915         } else if (verb > 3) {
916           fputs("INFO hash: ", stdout);
917           fhex(stdout, b.b.buf, b.b.len);
918           printf(" %s\n", b.d.buf);
919         }
920         bemit(&b, 0, s->h, 0);
921         break;
922       case T_SIGNATURE:
923         if (s->ops->doit(s, &b.b)) {
924           if (verb > 1)
925             puts("BAD bad signature");
926           f |= f_bogus;
927         } else if (verb > 2)
928           puts("INFO good signature");
929         goto done;
930       default:
931         if (verb)
932           printf("FAIL invalid packet type %i\n", e);
933         exit(EXIT_FAILURE);
934         break;
935     }
936     breset(&b);
937     e = bget(&b, fp, f & f_bin);
938     if (e < 0) {
939       if (verb)
940         printf("FAIL error reading packet: %s\n", errtab[-e]);
941       exit(EXIT_FAILURE);
942     }
943   }
944 done:
945   if ((f & FHF_JUNK) && fhash_junk(&fh, checkjunk, 0))
946     f |= f_bogus;
947   fhash_free(&fh);
948   bdestroy(&b);
949   dstr_destroy(&d);
950   freesig(s);
951   key_close(&kf);
952   if (fp != stdin)
953     fclose(fp);
954   if (verb) {
955     if (f & f_bogus)
956       puts("FAIL signature invalid");
957     else
958       puts("OK signature verified");
959   }
960   return (f & f_bogus ? EXIT_FAILURE : EXIT_SUCCESS);
961
962 #undef f_bogus
963 #undef f_bin
964 #undef f_ok
965 #undef f_nocheck
966 }
967
968 /*----- Main code ---------------------------------------------------------*/
969
970 #define LISTS(LI)                                                       \
971   LI("Lists", list,                                                     \
972      listtab[i].name, listtab[i].name)                                  \
973   LI("Signature schemes", sig,                                          \
974      sigtab[i].name, sigtab[i].name)                                    \
975   LI("Hash functions", hash,                                            \
976      ghashtab[i], ghashtab[i]->name)
977
978 MAKELISTTAB(listtab, LISTS)
979
980 int cmd_show(int argc, char *argv[])
981 {
982   return (displaylists(listtab, argv + 1));
983 }
984
985 static int cmd_help(int, char **);
986
987 static cmd cmdtab[] = {
988   { "help", cmd_help, "help [COMMAND...]" },
989   { "show", cmd_show, "show [ITEM...]" },
990   { "sign", sign,
991     "sign [-0bpqvC] [-c COMMENT] [-k TAG] [-e EXPIRE]\n\t\
992 [-f FILE] [-h FILE] [-o OUTPUT]",
993     "\
994 Options:\n\
995 \n\
996 -0, --null              Read null-terminated filenames from stdin.\n\
997 -b, --binary            Produce a binary output file.\n\
998 -q, --quiet             Produce fewer messages while working.\n\
999 -v, --verbose           Produce more messages while working.\n\
1000 -p, --progress          Show progress on large files.\n\
1001 -C, --nocheck           Don't check the private key.\n\
1002 -c, --comment=COMMENT   Include COMMENT in the output file.\n\
1003 -f, --file=FILE         Read filenames to hash from FILE.\n\
1004 -h, --hashes=FILE       Read precomputed hashes from FILE.\n\
1005 -o, --output=FILE       Write the signed result to FILE.\n\
1006 -k, --key=TAG           Use a key named by TAG.\n\
1007 -e, --expire=TIME       The signature should expire after TIME.\n\
1008 " },
1009   { "verify", verify,
1010     "verify [-pqvC] [FILE]", "\
1011 Options:\n\
1012 \n\
1013 -q, --quiet             Produce fewer messages while working.\n\
1014 -v, --verbose           Produce more messages while working.\n\
1015 -p, --progress          Show progress on large files.\n\
1016 -C, --nocheck           Don't check the public key.\n\
1017 " },
1018   { 0, 0, 0 }
1019 };
1020
1021 static int cmd_help(int argc, char **argv)
1022 {
1023   sc_help(cmdtab, stdout, argv + 1);
1024   return (0);
1025 }
1026
1027 void version(FILE *fp)
1028 {
1029   pquis(fp, "$, Catacomb version " VERSION "\n");
1030 }
1031
1032 static void usage(FILE *fp)
1033 {
1034   pquis(fp, "Usage: $ [-k KEYRING] COMMAND [ARGS]\n");
1035 }
1036
1037 void help_global(FILE *fp)
1038 {
1039   usage(fp);
1040   fputs("\n\
1041 Create and verify signatures on lists of files.\n\
1042 \n\
1043 Global command-line options:\n\
1044 \n\
1045 -h, --help [COMMAND...] Show this help message, or help for COMMANDs.\n\
1046 -v, --version           Show program version number.\n\
1047 -u, --usage             Show a terse usage message.\n\
1048 \n\
1049 -k, --keyring=FILE      Read keys from FILE.\n",
1050         fp);
1051 }
1052
1053 /* --- @main@ --- *
1054  *
1055  * Arguments:   @int argc@ = number of command line arguments
1056  *              @char *argv[]@ = vector of command line arguments
1057  *
1058  * Returns:     Zero if successful, nonzero otherwise.
1059  *
1060  * Use:         Signs or verifies signatures on lists of files.  Useful for
1061  *              ensuring that a distribution is unmolested.
1062  */
1063
1064 int main(int argc, char *argv[])
1065 {
1066   unsigned f = 0;
1067
1068 #define f_bogus 1u
1069
1070   /* --- Initialize the library --- */
1071
1072   ego(argv[0]);
1073   sub_init();
1074   rand_noisesrc(RAND_GLOBAL, &noise_source);
1075   rand_seed(RAND_GLOBAL, 160);
1076
1077   /* --- Parse options --- */
1078
1079   for (;;) {
1080     static struct option opts[] = {
1081       { "help",         0,              0,      'h' },
1082       { "version",      0,              0,      'v' },
1083       { "usage",        0,              0,      'u' },
1084       { "keyring",      OPTF_ARGREQ,    0,      'k' },
1085       { 0,              0,              0,      0 }
1086     };
1087     int i = mdwopt(argc, argv, "+hvu k:", opts, 0, 0, 0);
1088     if (i < 0)
1089       break;
1090     switch (i) {
1091       case 'h':
1092         sc_help(cmdtab, stdout, argv + optind);
1093         exit(0);
1094         break;
1095       case 'v':
1096         version(stdout);
1097         exit(0);
1098         break;
1099       case 'u':
1100         usage(stdout);
1101         exit(0);
1102       case 'k':
1103         keyring = optarg;
1104         break;
1105       default:
1106         f |= f_bogus;
1107         break;
1108     }
1109   }
1110
1111   argc -= optind;
1112   argv += optind;
1113   optind = 0;
1114   if (f & f_bogus || argc < 1) {
1115     usage(stderr);
1116     exit(EXIT_FAILURE);
1117   }
1118
1119   /* --- Dispatch to the correct subcommand handler --- */
1120
1121   return (findcmd(cmdtab, argv[0])->cmd(argc, argv));
1122
1123 #undef f_bogus
1124 }
1125
1126 /*----- That's all, folks -------------------------------------------------*/