veriexecgen.c revision 1.14 1 /* $NetBSD: veriexecgen.c,v 1.14 2007/01/16 17:32:04 hubertf Exp $ */
2
3 /*-
4 * Copyright (c) 2006 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Matt Fleming.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of The NetBSD Foundation nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 */
34 #if HAVE_NBTOOL_CONFIG_H
35 #include "nbtool_config.h"
36 #endif
37
38 #include <sys/cdefs.h>
39
40 #ifndef lint
41 #ifdef __RCSID
42 __RCSID("$NetBSD: veriexecgen.c,v 1.14 2007/01/16 17:32:04 hubertf Exp $");
43 #endif
44 #endif /* not lint */
45
46 #include <sys/param.h>
47 #include <sys/types.h>
48 #include <sys/queue.h>
49 #include <sys/stat.h>
50 #include <sys/dirent.h>
51 #include <sys/verified_exec.h>
52
53 #include <err.h>
54 #include <errno.h>
55 #include <fts.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <time.h>
60 #include <unistd.h>
61 #include <util.h>
62
63 #include <md5.h>
64 #include <sha1.h>
65 #include <sha2.h>
66 #include <rmd160.h>
67
68 #define IS_EXEC(mode) ((mode) & (S_IXUSR | S_IXGRP | S_IXOTH))
69
70 #define DEFAULT_DBFILE "/etc/signatures"
71 #define DEFAULT_HASH "sha256"
72 #define DEFAULT_SYSPATHS { "/bin", "/sbin", "/usr/bin", "/usr/sbin", \
73 "/lib", "/usr/lib", "/libexec", "/usr/libexec", \
74 NULL }
75
76 /* this struct defines a hash algorithm */
77 typedef struct hash_t {
78 const char *hashname; /* algorithm name */
79 char *(*filefunc)(const char *, char *); /* function */
80 } hash_t;
81
82 /* this struct encapsulates various diverse options and arguments */
83 typedef struct veriexecgen_t {
84 int all_files; /* scan also for non-executable files */
85 int append_output; /* append output to existing sigs file */
86 char *dbfile; /* name of signatures database file */
87 int exit_on_error; /* exit if we can't create a hash */
88 char *prefix; /* any prefix to be discarded on output */
89 int recursive_scan;/* perform scan for files recursively */
90 int scan_system_dirs; /* just scan system directories */
91 int verbose; /* verbosity level */
92 } veriexecgen_t;
93
94 /* this struct describes a directory entry to generate a hash for */
95 struct fentry {
96 char filename[MAXPATHLEN]; /* name of entry */
97 char *hash_val; /* its associated hash value */
98 int flags; /* any associated flags */
99 TAILQ_ENTRY(fentry) f; /* its place in the queue */
100 };
101 TAILQ_HEAD(, fentry) fehead;
102
103 /* define the possible hash algorithms */
104 static hash_t hashes[] = {
105 { "MD5", MD5File },
106 { "SHA1", SHA1File },
107 { "SHA256", SHA256_File },
108 { "SHA384", SHA384_File },
109 { "SHA512", SHA512_File },
110 { "RMD160", RMD160File },
111 { NULL, NULL },
112 };
113
114 static int Fflag;
115
116 static int make_immutable; /* set immutable flag on signatures file */
117
118 /* warn about a problem - exit if exit_on_error is set */
119 static void
120 gripe(veriexecgen_t *vp, const char *fmt, const char *filename)
121 {
122 warn(fmt, filename);
123 if (vp->exit_on_error) {
124 /* error out on problematic files */
125 exit(EXIT_FAILURE);
126 }
127 }
128
129 /* print usage message */
130 static void
131 usage(void)
132 {
133 (void)fprintf(stderr,
134 "usage: %s [-AaDrSvW] [-d dir] [-o fingerprintdb] [-p prefix]\n"
135 "\t\t [-t algorithm]\n"
136 "\t%s [-h]\n", getprogname(), getprogname());
137 }
138
139 /* tell people what we're doing - scan dirs, fingerprint etc */
140 static void
141 banner(veriexecgen_t *vp, hash_t *hash_type, char **search_path)
142 {
143 int j;
144
145 (void)printf("Fingerprinting ");
146
147 for (j = 0; search_path[j] != NULL; j++)
148 (void)printf("%s ", search_path[j]);
149
150 (void)printf("(%s) (%s) using %s\n",
151 vp->all_files ? "all files" : "executables only",
152 vp->recursive_scan ? "recursive" : "non-recursive",
153 hash_type->hashname);
154 }
155
156 /* find a hash algorithm, given its name */
157 static hash_t *
158 find_hash(char *hash_type)
159 {
160 hash_t *hash;
161
162 for (hash = hashes; hash->hashname != NULL; hash++)
163 if (strcasecmp(hash_type, hash->hashname) == 0)
164 return hash;
165 return NULL;
166 }
167
168 /* perform the hashing operation on `filename' */
169 static char *
170 do_hash(char *filename, hash_t * h)
171 {
172 return h->filefunc(filename, NULL);
173 }
174
175 /* return flags for `path' */
176 static int
177 figure_flags(char *path, mode_t mode)
178 {
179 #ifdef notyet
180 if (Fflag) {
181 /* Try to figure out right flag(s). */
182 return VERIEXEC_DIRECT;
183 }
184 #endif /* notyet */
185
186 return (IS_EXEC(mode)) ? 0 : VERIEXEC_FILE;
187 }
188
189 /* check to see that we don't have a duplicate entry */
190 static int
191 check_dup(char *filename)
192 {
193 struct fentry *lwalk;
194
195 TAILQ_FOREACH(lwalk, &fehead, f) {
196 if (strncmp(lwalk->filename, filename,
197 (unsigned long) MAXPATHLEN) == 0)
198 return 1;
199 }
200
201 return 0;
202 }
203
204 /* add a new entry to the list for `file' */
205 static void
206 add_new_entry(veriexecgen_t *vp, FTSENT *file, hash_t *hash)
207 {
208 struct fentry *e;
209 struct stat sb;
210
211 if (file->fts_info == FTS_SL) {
212 /* we have a symbolic link */
213 if (stat(file->fts_path, &sb) == -1) {
214 gripe(vp, "Cannot stat symlink `%s'", file->fts_path);
215 return;
216 }
217 } else
218 sb = *file->fts_statp;
219
220 if (!vp->all_files && !vp->scan_system_dirs && !IS_EXEC(sb.st_mode))
221 return;
222
223 e = ecalloc(1UL, sizeof(*e));
224
225 if (realpath(file->fts_accpath, e->filename) == NULL) {
226 gripe(vp, "Cannot find absolute path `%s'", file->fts_accpath);
227 return;
228 }
229 if (check_dup(e->filename)) {
230 free(e);
231 return;
232 }
233 if ((e->hash_val = do_hash(e->filename, hash)) == NULL) {
234 gripe(vp, "Cannot calculate hash `%s'", e->filename);
235 return;
236 }
237 e->flags = figure_flags(e->filename, sb.st_mode);
238
239 TAILQ_INSERT_TAIL(&fehead, e, f);
240 }
241
242 /* walk through a directory */
243 static void
244 walk_dir(veriexecgen_t *vp, char **search_path, hash_t *hash)
245 {
246 FTS *fh;
247 FTSENT *file;
248
249 if ((fh = fts_open(search_path, FTS_PHYSICAL, NULL)) == NULL) {
250 gripe(vp, "fts_open `%s'", (const char *)search_path);
251 return;
252 }
253
254 while ((file = fts_read(fh)) != NULL) {
255 if (!vp->recursive_scan && file->fts_level > 1) {
256 fts_set(fh, file, FTS_SKIP);
257 continue;
258 }
259
260 switch (file->fts_info) {
261 case FTS_D:
262 case FTS_DC:
263 case FTS_DP:
264 continue;
265 default:
266 break;
267 }
268
269 if (file->fts_errno) {
270 if (vp->exit_on_error) {
271 errx(EXIT_FAILURE, "%s: %s", file->fts_path,
272 strerror(file->fts_errno));
273 }
274 } else {
275 add_new_entry(vp, file, hash);
276 }
277 }
278
279 fts_close(fh);
280 }
281
282 /* return a string representation of the flags */
283 static char *
284 flags2str(int flags)
285 {
286 return (flags == 0) ? "" : "FILE, INDIRECT";
287 }
288
289 /* store the list in the signatures file */
290 static void
291 store_entries(veriexecgen_t *vp, hash_t *hash)
292 {
293 FILE *fp;
294 int move = 1;
295 char old_dbfile[MAXPATHLEN];
296 time_t ct;
297 struct stat sb;
298 struct fentry *e;
299 int prefixc;
300
301 if (stat(vp->dbfile, &sb) != 0) {
302 if (errno == ENOENT)
303 move = 0;
304 else
305 err(EXIT_FAILURE, "could not stat %s", vp->dbfile);
306 }
307 if (move && !vp->append_output) {
308 if (vp->verbose)
309 (void)printf("\nBacking up existing fingerprint file "
310 "to \"%s.old\"\n\n", vp->dbfile);
311
312 if (snprintf(old_dbfile, MAXPATHLEN, "%s.old", vp->dbfile) <
313 strlen(vp->dbfile) + 4) {
314 err(EXIT_FAILURE, "%s", old_dbfile);
315 }
316 if (rename(vp->dbfile, old_dbfile) == -1)
317 err(EXIT_FAILURE, "could not rename file");
318 }
319
320 prefixc = (vp->prefix == NULL) ? -1 : strlen(vp->prefix);
321
322 fp = efopen(vp->dbfile, vp->append_output ? "a" : "w+");
323
324 time(&ct);
325 (void)fprintf(fp, "# Generated by %s, %.24s\n",
326 getlogin(), ctime(&ct));
327
328 TAILQ_FOREACH(e, &fehead, f) {
329 if (vp->verbose)
330 (void)printf("Adding %s.\n", e->filename);
331
332
333 (void)fprintf(fp, "%s %s %s %s\n",
334 (prefixc < 0) ? e->filename : &e->filename[prefixc],
335 hash->hashname, e->hash_val, flags2str(e->flags));
336 }
337
338 (void)fclose(fp);
339
340 if (vp->verbose) {
341 (void)printf("\n\n"
342 "#############################################################\n"
343 " PLEASE VERIFY CONTENTS OF %s AND FINE-TUNE THE\n"
344 " FLAGS WHERE APPROPRIATE AFTER READING veriexecctl(8)\n"
345 "#############################################################\n",
346 vp->dbfile);
347 }
348 }
349
350 int
351 main(int argc, char **argv)
352 {
353 int ch, total = 0;
354 char **search_path = NULL;
355 hash_t *hash = NULL;
356 veriexecgen_t v;
357
358 (void) memset(&v, 0x0, sizeof(v));
359 make_immutable = 0;
360 Fflag = 0;
361
362 /* error out if we have a dangling symlink or other fs problem */
363 v.exit_on_error = 1;
364
365 while ((ch = getopt(argc, argv, "AaDd:ho:p:rSt:vW")) != -1) {
366 switch (ch) {
367 case 'A':
368 v.append_output = 1;
369 break;
370 case 'a':
371 v.all_files = 1;
372 break;
373 case 'D':
374 v.scan_system_dirs = 1;
375 break;
376 case 'd':
377 search_path = erealloc(search_path, sizeof(char *) *
378 (total + 1));
379 search_path[total] = optarg;
380 search_path[++total] = NULL;
381 break;
382 #ifdef notyet
383 case 'F':
384 Fflag = 1;
385 break;
386 #endif /* notyet */
387 case 'h':
388 usage();
389 return EXIT_SUCCESS;
390 case 'o':
391 v.dbfile = optarg;
392 break;
393 case 'p':
394 v.prefix = optarg;
395 break;
396 case 'r':
397 v.recursive_scan = 1;
398 break;
399 case 'S':
400 make_immutable = 1;
401 break;
402 case 't':
403 if ((hash = find_hash(optarg)) == NULL) {
404 errx(EXIT_FAILURE,
405 "No such hash algorithm (%s)",
406 optarg);
407 }
408 break;
409 case 'v':
410 v.verbose = 1;
411 break;
412 case 'W':
413 v.exit_on_error = 0;
414 break;
415 default:
416 usage();
417 return EXIT_FAILURE;
418 }
419 }
420
421 if (v.dbfile == NULL)
422 v.dbfile = DEFAULT_DBFILE;
423
424 if (hash == NULL) {
425 if ((hash = find_hash(DEFAULT_HASH)) == NULL)
426 errx(EXIT_FAILURE, "No hash algorithm");
427 }
428
429 TAILQ_INIT(&fehead);
430
431 if (search_path == NULL)
432 v.scan_system_dirs = 1;
433
434 if (v.scan_system_dirs) {
435 char *sys_paths[] = DEFAULT_SYSPATHS;
436
437 if (v.verbose)
438 banner(&v, hash, sys_paths);
439 walk_dir(&v, sys_paths, hash);
440 }
441
442 if (search_path != NULL) {
443 if (v.verbose)
444 banner(&v, hash, search_path);
445 walk_dir(&v, search_path, hash);
446 }
447
448 store_entries(&v, hash);
449
450 if (make_immutable && chflags(v.dbfile, SF_IMMUTABLE) != 0)
451 err(EXIT_FAILURE, "Can't set immutable flag");
452
453 return EXIT_SUCCESS;
454 }
455