Home | History | Annotate | Line # | Download | only in veriexecgen
veriexecgen.c revision 1.12
      1 /* $NetBSD: veriexecgen.c,v 1.12 2006/12/23 09:16:38 wiz 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.12 2006/12/23 09:16:38 wiz 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] [-p prefix]\n"
    141 	    "\t\t    [-t algorithm]\n"
    142 	    "\t%s [-h]\n", getprogname(), getprogname());
    143 }
    144 
    145 /* tell people what we're doing - scan dirs, fingerprint etc */
    146 static void
    147 banner(veriexecgen_t *vp, hash_t *hash_type, char **search_path)
    148 {
    149 	int j;
    150 
    151 	(void)printf("Fingerprinting ");
    152 
    153 	for (j = 0; search_path[j] != NULL; j++)
    154 		(void)printf("%s ", search_path[j]);
    155 
    156 	(void)printf("(%s) (%s) using %s\n",
    157 	    vp->all_files ? "all files" : "executables only",
    158 	    vp->recursive_scan ? "recursive" : "non-recursive",
    159 	    hash_type->hashname);
    160 }
    161 
    162 /* find a hash algorithm, given its name */
    163 static hash_t *
    164 find_hash(char *hash_type)
    165 {
    166 	hash_t *hash;
    167 
    168 	for (hash = hashes; hash->hashname != NULL; hash++)
    169 		if (strcasecmp(hash_type, hash->hashname) == 0)
    170 			return hash;
    171 	return NULL;
    172 }
    173 
    174 /* perform the hashing operation on `filename' */
    175 static char *
    176 do_hash(char *filename, hash_t * h)
    177 {
    178 	return h->filefunc(filename, NULL);
    179 }
    180 
    181 /* return flags for `path' */
    182 static int
    183 figure_flags(char *path, mode_t mode)
    184 {
    185 #ifdef notyet
    186 	if (Fflag) {
    187 		/* Try to figure out right flag(s). */
    188 		return VERIEXEC_DIRECT;
    189 	}
    190 #endif /* notyet */
    191 
    192 	return (IS_EXEC(mode)) ? 0 : VERIEXEC_FILE;
    193 }
    194 
    195 /* check to see that we don't have a duplicate entry */
    196 static int
    197 check_dup(char *filename)
    198 {
    199 	struct fentry *lwalk;
    200 
    201 	TAILQ_FOREACH(lwalk, &fehead, f) {
    202 		if (strncmp(lwalk->filename, filename,
    203 			    (unsigned long) MAXPATHLEN) == 0)
    204 			return 1;
    205 	}
    206 
    207 	return 0;
    208 }
    209 
    210 /* add a new entry to the list for `file' */
    211 static void
    212 add_new_entry(veriexecgen_t *vp, FTSENT *file, hash_t *hash)
    213 {
    214 	struct fentry *e;
    215 	struct stat sb;
    216 
    217 	if (file->fts_info == FTS_SL) {
    218 		/* we have a symbolic link */
    219 		if (stat(file->fts_path, &sb) == -1) {
    220 			gripe(vp, "Cannot stat symlink `%s'", file->fts_path);
    221 			return;
    222 		}
    223 	} else
    224 		sb = *file->fts_statp;
    225 
    226 	if (!vp->all_files && !vp->scan_system_dirs && !IS_EXEC(sb.st_mode))
    227 		return;
    228 
    229 	e = ecalloc(1UL, sizeof(*e));
    230 
    231 	if (realpath(file->fts_accpath, e->filename) == NULL) {
    232 		gripe(vp, "Cannot find absolute path `%s'", file->fts_accpath);
    233 		return;
    234 	}
    235 	if (check_dup(e->filename)) {
    236 		free(e);
    237 		return;
    238 	}
    239 	if ((e->hash_val = do_hash(e->filename, hash)) == NULL) {
    240 		gripe(vp, "Cannot calculate hash `%s'", e->filename);
    241 		return;
    242 	}
    243 	e->flags = figure_flags(e->filename, sb.st_mode);
    244 
    245 	TAILQ_INSERT_TAIL(&fehead, e, f);
    246 }
    247 
    248 /* walk through a directory */
    249 static void
    250 walk_dir(veriexecgen_t *vp, char **search_path, hash_t *hash)
    251 {
    252 	FTS *fh;
    253 	FTSENT *file;
    254 
    255 	if ((fh = fts_open(search_path, FTS_PHYSICAL, NULL)) == NULL) {
    256 		gripe(vp, "fts_open `%s'", (const char *)search_path);
    257 		return;
    258 	}
    259 
    260 	while ((file = fts_read(fh)) != NULL) {
    261 		if (!vp->recursive_scan && file->fts_level > 1) {
    262 			fts_set(fh, file, FTS_SKIP);
    263 			continue;
    264 		}
    265 
    266 		switch (file->fts_info) {
    267 		case FTS_D:
    268 		case FTS_DC:
    269 		case FTS_DP:
    270 			continue;
    271 		default:
    272 			break;
    273 		}
    274 
    275 		if (file->fts_errno) {
    276 			if (vp->exit_on_error) {
    277 				errx(EXIT_FAILURE, "%s: %s", file->fts_path,
    278 				    strerror(file->fts_errno));
    279 			}
    280 		} else {
    281 			add_new_entry(vp, file, hash);
    282 		}
    283 	}
    284 
    285 	fts_close(fh);
    286 }
    287 
    288 /* return a string representation of the flags */
    289 static char *
    290 flags2str(int flags)
    291 {
    292 	return (flags == 0) ? "" : "FILE, INDIRECT";
    293 }
    294 
    295 /* store the list in the signatures file */
    296 static void
    297 store_entries(veriexecgen_t *vp, hash_t *hash)
    298 {
    299 	FILE *fp;
    300 	int move = 1;
    301 	char old_dbfile[MAXPATHLEN];
    302 	time_t ct;
    303 	struct stat sb;
    304 	struct fentry  *e;
    305 	int	prefixc;
    306 
    307 	if (stat(vp->dbfile, &sb) != 0) {
    308 		if (errno == ENOENT)
    309 			move = 0;
    310 		else
    311 			err(EXIT_FAILURE, "could not stat %s", vp->dbfile);
    312 	}
    313 	if (move && !vp->append_output) {
    314 		if (vp->verbose)
    315 			(void)printf("\nBacking up existing fingerprint file "
    316 			    "to \"%s.old\"\n\n", vp->dbfile);
    317 
    318 		if (snprintf(old_dbfile, MAXPATHLEN, "%s.old", vp->dbfile) <
    319 		    strlen(vp->dbfile) + 4) {
    320 			err(EXIT_FAILURE, "%s", old_dbfile);
    321 		}
    322 		if (rename(vp->dbfile, old_dbfile) == -1)
    323 			err(EXIT_FAILURE, "could not rename file");
    324 	}
    325 
    326 	prefixc = (vp->prefix == NULL) ? -1 : strlen(vp->prefix);
    327 
    328 	fp = efopen(vp->dbfile, vp->append_output ? "a" : "w+");
    329 
    330 	time(&ct);
    331 	(void)fprintf(fp, "# Generated by %s, %.24s\n",
    332 		getlogin(), ctime(&ct));
    333 
    334 	TAILQ_FOREACH(e, &fehead, f) {
    335 		if (vp->verbose)
    336 			(void)printf("Adding %s.\n", e->filename);
    337 
    338 
    339 		(void)fprintf(fp, "%s %s %s %s\n",
    340 			(prefixc < 0) ? e->filename : &e->filename[prefixc],
    341 			hash->hashname, e->hash_val, flags2str(e->flags));
    342 	}
    343 
    344 	(void)fclose(fp);
    345 
    346 	if (vp->verbose) {
    347 		(void)printf("\n\n"
    348 "#############################################################\n"
    349 "  PLEASE VERIFY CONTENTS OF %s AND FINE-TUNE THE\n"
    350 "  FLAGS WHERE APPROPRIATE AFTER READING veriexecctl(8)\n"
    351 "#############################################################\n",
    352 			vp->dbfile);
    353 	}
    354 }
    355 
    356 int
    357 main(int argc, char **argv)
    358 {
    359 	int ch, total = 0;
    360 	char **search_path = NULL;
    361 	hash_t *hash = NULL;
    362 	veriexecgen_t	v;
    363 
    364 	(void) memset(&v, 0x0, sizeof(v));
    365 	make_immutable = 0;
    366 	Fflag = 0;
    367 
    368 	/* error out if we have a dangling symlink or other fs problem */
    369 	v.exit_on_error = 1;
    370 
    371 	while ((ch = getopt(argc, argv, "AaDd:ho:p:rSt:vW")) != -1) {
    372 		switch (ch) {
    373 		case 'A':
    374 			v.append_output = 1;
    375 			break;
    376 		case 'a':
    377 			v.all_files = 1;
    378 			break;
    379 		case 'D':
    380 			v.scan_system_dirs = 1;
    381 			break;
    382 		case 'd':
    383 			search_path = erealloc(search_path, sizeof(char *) *
    384 			    (total + 1));
    385 			search_path[total] = optarg;
    386 			search_path[++total] = NULL;
    387 			break;
    388 #ifdef notyet
    389 		case 'F':
    390 			Fflag = 1;
    391 			break;
    392 #endif /* notyet */
    393 		case 'h':
    394 			usage();
    395 			return EXIT_SUCCESS;
    396 		case 'o':
    397 			v.dbfile = optarg;
    398 			break;
    399 		case 'p':
    400 			v.prefix = optarg;
    401 			break;
    402 		case 'r':
    403 			v.recursive_scan = 1;
    404 			break;
    405 		case 'S':
    406 			make_immutable = 1;
    407 			break;
    408 		case 't':
    409 			if ((hash = find_hash(optarg)) == NULL) {
    410 				errx(EXIT_FAILURE,
    411 					"No such hash algorithm (%s)",
    412 					optarg);
    413 			}
    414 			break;
    415 		case 'v':
    416 			v.verbose = 1;
    417 			break;
    418 		case 'W':
    419 			v.exit_on_error = 0;
    420 			break;
    421 		default:
    422 			usage();
    423 			return EXIT_FAILURE;
    424 		}
    425 	}
    426 
    427 	if (v.dbfile == NULL)
    428 		v.dbfile = DEFAULT_DBFILE;
    429 
    430 	if (hash == NULL) {
    431 		if ((hash = find_hash(DEFAULT_HASH)) == NULL)
    432 			errx(EXIT_FAILURE, "No hash algorithm");
    433 	}
    434 
    435 	TAILQ_INIT(&fehead);
    436 
    437 	if (search_path == NULL)
    438 		v.scan_system_dirs = 1;
    439 
    440 	if (v.scan_system_dirs) {
    441 		char *sys_paths[] = DEFAULT_SYSPATHS;
    442 
    443 		if (v.verbose)
    444 			banner(&v, hash, sys_paths);
    445 		walk_dir(&v, sys_paths, hash);
    446 	}
    447 
    448 	if (search_path != NULL) {
    449 		if (v.verbose)
    450 			banner(&v, hash, search_path);
    451 		walk_dir(&v, search_path, hash);
    452 	}
    453 
    454 	store_entries(&v, hash);
    455 
    456 	if (make_immutable && chflags(v.dbfile, SF_IMMUTABLE) != 0)
    457 		err(EXIT_FAILURE, "Can't set immutable flag");
    458 
    459 	return EXIT_SUCCESS;
    460 }
    461