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