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