Home | History | Annotate | Line # | Download | only in veriexecgen
veriexecgen.c revision 1.15
      1 /* $NetBSD: veriexecgen.c,v 1.15 2007/05/15 19:47:47 elad 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.15 2007/05/15 19:47:47 elad 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 	int	 stamp;		/* put a timestamp */
     93 } veriexecgen_t;
     94 
     95 /* this struct describes a directory entry to generate a hash for */
     96 struct fentry {
     97 	char filename[MAXPATHLEN];	/* name of entry */
     98 	char *hash_val;			/* its associated hash value */
     99 	int flags;			/* any associated flags */
    100 	TAILQ_ENTRY(fentry) f;		/* its place in the queue */
    101 };
    102 TAILQ_HEAD(, fentry) fehead;
    103 
    104 /* define the possible hash algorithms */
    105 static hash_t	 hashes[] = {
    106 	{ "MD5", MD5File },
    107 	{ "SHA1", SHA1File },
    108 	{ "SHA256", SHA256_File },
    109 	{ "SHA384", SHA384_File },
    110 	{ "SHA512", SHA512_File },
    111 	{ "RMD160", RMD160File },
    112 	{ NULL, NULL },
    113 };
    114 
    115 static int Fflag;
    116 
    117 static int	make_immutable;	/* set immutable flag on signatures file */
    118 
    119 /* warn about a problem - exit if exit_on_error is set */
    120 static void
    121 gripe(veriexecgen_t *vp, const char *fmt, const char *filename)
    122 {
    123 	warn(fmt, filename);
    124 	if (vp->exit_on_error) {
    125 		/* error out on problematic files */
    126 		exit(EXIT_FAILURE);
    127 	}
    128 }
    129 
    130 /* print usage message */
    131 static void
    132 usage(void)
    133 {
    134 	(void)fprintf(stderr,
    135 	    "usage:  %s [-AaDrSvW] [-d dir] [-o fingerprintdb] [-p prefix]\n"
    136 	    "\t\t    [-t algorithm]\n"
    137 	    "\t%s [-h]\n", getprogname(), getprogname());
    138 }
    139 
    140 /* tell people what we're doing - scan dirs, fingerprint etc */
    141 static void
    142 banner(veriexecgen_t *vp, hash_t *hash_type, char **search_path)
    143 {
    144 	int j;
    145 
    146 	(void)printf("Fingerprinting ");
    147 
    148 	for (j = 0; search_path[j] != NULL; j++)
    149 		(void)printf("%s ", search_path[j]);
    150 
    151 	(void)printf("(%s) (%s) using %s\n",
    152 	    vp->all_files ? "all files" : "executables only",
    153 	    vp->recursive_scan ? "recursive" : "non-recursive",
    154 	    hash_type->hashname);
    155 }
    156 
    157 /* find a hash algorithm, given its name */
    158 static hash_t *
    159 find_hash(char *hash_type)
    160 {
    161 	hash_t *hash;
    162 
    163 	for (hash = hashes; hash->hashname != NULL; hash++)
    164 		if (strcasecmp(hash_type, hash->hashname) == 0)
    165 			return hash;
    166 	return NULL;
    167 }
    168 
    169 /* perform the hashing operation on `filename' */
    170 static char *
    171 do_hash(char *filename, hash_t * h)
    172 {
    173 	return h->filefunc(filename, NULL);
    174 }
    175 
    176 /* return flags for `path' */
    177 static int
    178 figure_flags(char *path, mode_t mode)
    179 {
    180 #ifdef notyet
    181 	if (Fflag) {
    182 		/* Try to figure out right flag(s). */
    183 		return VERIEXEC_DIRECT;
    184 	}
    185 #endif /* notyet */
    186 
    187 	return (IS_EXEC(mode)) ? 0 : VERIEXEC_FILE;
    188 }
    189 
    190 /* check to see that we don't have a duplicate entry */
    191 static int
    192 check_dup(char *filename)
    193 {
    194 	struct fentry *lwalk;
    195 
    196 	TAILQ_FOREACH(lwalk, &fehead, f) {
    197 		if (strcmp(lwalk->filename, filename) == 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 static char *
    290 escape(const char *s)
    291 {
    292 	char *q, *p;
    293 	size_t len;
    294 
    295 	len = strlen(s);
    296 	if (len >= MAXPATHLEN)
    297 		return (NULL);
    298 
    299 	len *= 2;
    300 	q = p = calloc(1, len + 1);
    301 
    302 	while (*s) {
    303 		if (*s == ' ' || *s == '\t')
    304 			*p++ = '\\';
    305 
    306 		*p++ = *s++;
    307 	}
    308 
    309 	return (q);
    310 }
    311 
    312 /* store the list in the signatures file */
    313 static void
    314 store_entries(veriexecgen_t *vp, hash_t *hash)
    315 {
    316 	FILE *fp;
    317 	int move = 1;
    318 	char old_dbfile[MAXPATHLEN];
    319 	time_t ct;
    320 	struct stat sb;
    321 	struct fentry  *e;
    322 	int	prefixc;
    323 
    324 	if (stat(vp->dbfile, &sb) != 0) {
    325 		if (errno == ENOENT)
    326 			move = 0;
    327 		else
    328 			err(EXIT_FAILURE, "could not stat %s", vp->dbfile);
    329 	}
    330 	if (move && !vp->append_output) {
    331 		if (vp->verbose)
    332 			(void)printf("\nBacking up existing fingerprint file "
    333 			    "to \"%s.old\"\n\n", vp->dbfile);
    334 
    335 		if (snprintf(old_dbfile, sizeof(old_dbfile), "%s.old",
    336 		    vp->dbfile) < strlen(vp->dbfile) + 4) {
    337 			err(EXIT_FAILURE, "%s", old_dbfile);
    338 		}
    339 		if (rename(vp->dbfile, old_dbfile) == -1)
    340 			err(EXIT_FAILURE, "could not rename file");
    341 	}
    342 
    343 	prefixc = (vp->prefix == NULL) ? -1 : strlen(vp->prefix);
    344 
    345 	fp = efopen(vp->dbfile, vp->append_output ? "a" : "w+");
    346 
    347 	if (vp->stamp) {
    348 		time(&ct);
    349 		(void)fprintf(fp, "# Generated by %s, %.24s\n",
    350 			getlogin(), ctime(&ct));
    351 	}
    352 
    353 	TAILQ_FOREACH(e, &fehead, f) {
    354 		char *file;
    355 
    356 		if (vp->verbose)
    357 			(void)printf("Adding %s.\n", e->filename);
    358 
    359 		file = (prefixc < 0) ? e->filename : &e->filename[prefixc];
    360 		file = escape(file);
    361 
    362 		(void)fprintf(fp, "%s %s %s %s\n", file, hash->hashname,
    363 		    e->hash_val, flags2str(e->flags));
    364 
    365 		free(file);
    366 	}
    367 
    368 	(void)fclose(fp);
    369 
    370 	if (vp->verbose) {
    371 		(void)printf("\n\n"
    372 "#############################################################\n"
    373 "  PLEASE VERIFY CONTENTS OF %s AND FINE-TUNE THE\n"
    374 "  FLAGS WHERE APPROPRIATE AFTER READING veriexecctl(8)\n"
    375 "#############################################################\n",
    376 			vp->dbfile);
    377 	}
    378 }
    379 
    380 int
    381 main(int argc, char **argv)
    382 {
    383 	int ch, total = 0;
    384 	char **search_path = NULL;
    385 	hash_t *hash = NULL;
    386 	veriexecgen_t	v;
    387 
    388 	(void) memset(&v, 0x0, sizeof(v));
    389 	make_immutable = 0;
    390 	Fflag = 0;
    391 
    392 	/* error out if we have a dangling symlink or other fs problem */
    393 	v.exit_on_error = 1;
    394 
    395 	while ((ch = getopt(argc, argv, "AaDd:ho:p:rSt:vW")) != -1) {
    396 		switch (ch) {
    397 		case 'A':
    398 			v.append_output = 1;
    399 			break;
    400 		case 'a':
    401 			v.all_files = 1;
    402 			break;
    403 		case 'D':
    404 			v.scan_system_dirs = 1;
    405 			break;
    406 		case 'd':
    407 			search_path = erealloc(search_path, sizeof(char *) *
    408 			    (total + 1));
    409 			search_path[total] = optarg;
    410 			search_path[++total] = NULL;
    411 			break;
    412 #ifdef notyet
    413 		case 'F':
    414 			Fflag = 1;
    415 			break;
    416 #endif /* notyet */
    417 		case 'h':
    418 			usage();
    419 			return EXIT_SUCCESS;
    420 		case 'o':
    421 			v.dbfile = optarg;
    422 			break;
    423 		case 'p':
    424 			v.prefix = optarg;
    425 			break;
    426 		case 'r':
    427 			v.recursive_scan = 1;
    428 			break;
    429 		case 'S':
    430 			make_immutable = 1;
    431 			break;
    432 		case 'T':
    433 			v.stamp = 1;
    434 			break;
    435 		case 't':
    436 			if ((hash = find_hash(optarg)) == NULL) {
    437 				errx(EXIT_FAILURE,
    438 					"No such hash algorithm (%s)",
    439 					optarg);
    440 			}
    441 			break;
    442 		case 'v':
    443 			v.verbose = 1;
    444 			break;
    445 		case 'W':
    446 			v.exit_on_error = 0;
    447 			break;
    448 		default:
    449 			usage();
    450 			return EXIT_FAILURE;
    451 		}
    452 	}
    453 
    454 	if (v.dbfile == NULL)
    455 		v.dbfile = DEFAULT_DBFILE;
    456 
    457 	if (hash == NULL) {
    458 		if ((hash = find_hash(DEFAULT_HASH)) == NULL)
    459 			errx(EXIT_FAILURE, "No hash algorithm");
    460 	}
    461 
    462 	TAILQ_INIT(&fehead);
    463 
    464 	if (search_path == NULL)
    465 		v.scan_system_dirs = 1;
    466 
    467 	if (v.scan_system_dirs) {
    468 		char *sys_paths[] = DEFAULT_SYSPATHS;
    469 
    470 		if (v.verbose)
    471 			banner(&v, hash, sys_paths);
    472 		walk_dir(&v, sys_paths, hash);
    473 	}
    474 
    475 	if (search_path != NULL) {
    476 		if (v.verbose)
    477 			banner(&v, hash, search_path);
    478 		walk_dir(&v, search_path, hash);
    479 	}
    480 
    481 	store_entries(&v, hash);
    482 
    483 	if (make_immutable && chflags(v.dbfile, SF_IMMUTABLE) != 0)
    484 		err(EXIT_FAILURE, "Can't set immutable flag");
    485 
    486 	return EXIT_SUCCESS;
    487 }
    488