Home | History | Annotate | Line # | Download | only in kern
kern_veriexec.c revision 1.18.6.2
      1 /*	$NetBSD: kern_veriexec.c,v 1.18.6.2 2020/04/08 14:08:51 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2005, 2006 Elad Efrat <elad (at) NetBSD.org>
      5  * Copyright (c) 2005, 2006 Brett Lymn <blymn (at) NetBSD.org>
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. The name of the authors may not be used to endorse or promote products
     17  *    derived from this software without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
     20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     22  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 #include <sys/cdefs.h>
     32 __KERNEL_RCSID(0, "$NetBSD: kern_veriexec.c,v 1.18.6.2 2020/04/08 14:08:51 martin Exp $");
     33 
     34 #include "opt_veriexec.h"
     35 
     36 #include <sys/param.h>
     37 #include <sys/mount.h>
     38 #include <sys/kmem.h>
     39 #include <sys/vnode.h>
     40 #include <sys/namei.h>
     41 #include <sys/once.h>
     42 #include <sys/proc.h>
     43 #include <sys/rwlock.h>
     44 #include <sys/syslog.h>
     45 #include <sys/sysctl.h>
     46 #include <sys/inttypes.h>
     47 #include <sys/verified_exec.h>
     48 #include <sys/sha1.h>
     49 #include <sys/sha2.h>
     50 #include <sys/rmd160.h>
     51 #include <sys/md5.h>
     52 #include <sys/fileassoc.h>
     53 #include <sys/kauth.h>
     54 #include <sys/conf.h>
     55 #include <miscfs/specfs/specdev.h>
     56 #include <prop/proplib.h>
     57 #include <sys/fcntl.h>
     58 
     59 /* Readable values for veriexec_file_report(). */
     60 #define	REPORT_ALWAYS		0x01	/* Always print */
     61 #define	REPORT_VERBOSE		0x02	/* Print when verbose >= 1 */
     62 #define	REPORT_DEBUG		0x04	/* Print when verbose >= 2 (debug) */
     63 #define	REPORT_PANIC		0x08	/* Call panic() */
     64 #define	REPORT_ALARM		0x10	/* Alarm - also print pid/uid/.. */
     65 #define	REPORT_LOGMASK		(REPORT_ALWAYS|REPORT_VERBOSE|REPORT_DEBUG)
     66 
     67 /* state of locking for veriexec_file_verify */
     68 #define VERIEXEC_UNLOCKED	0x00	/* Nothing locked, callee does it */
     69 #define VERIEXEC_LOCKED		0x01	/* Global op lock held */
     70 
     71 /* state of file locking for veriexec_file_verify */
     72 #define VERIEXEC_FILE_UNLOCKED	0x02	/* Nothing locked, callee does it */
     73 #define VERIEXEC_FILE_LOCKED	0x04	/* File locked */
     74 
     75 #define VERIEXEC_RW_UPGRADE(lock)	while((rw_tryupgrade(lock)) == 0){};
     76 
     77 struct veriexec_fpops {
     78 	const char *type;
     79 	size_t hash_len;
     80 	size_t context_size;
     81 	veriexec_fpop_init_t init;
     82 	veriexec_fpop_update_t update;
     83 	veriexec_fpop_final_t final;
     84 	LIST_ENTRY(veriexec_fpops) entries;
     85 };
     86 
     87 /* Veriexec per-file entry data. */
     88 struct veriexec_file_entry {
     89 	krwlock_t lock;				/* r/w lock */
     90 	u_char *filename;			/* File name. */
     91 	u_char type;				/* Entry type. */
     92 	u_char status;				/* Evaluation status. */
     93 	u_char *fp;				/* Fingerprint. */
     94 	struct veriexec_fpops *ops;		/* Fingerprint ops vector*/
     95 	size_t filename_len;			/* Length of filename. */
     96 };
     97 
     98 /* Veriexec per-table data. */
     99 struct veriexec_table_entry {
    100 	uint64_t vte_count;			/* Number of Veriexec entries. */
    101 	const struct sysctlnode *vte_node;
    102 };
    103 
    104 static int veriexec_verbose;
    105 static int veriexec_strict;
    106 static int veriexec_bypass = 1;
    107 
    108 static char *veriexec_fp_names = NULL;
    109 static size_t veriexec_name_max = 0;
    110 
    111 static const struct sysctlnode *veriexec_count_node;
    112 
    113 static fileassoc_t veriexec_hook;
    114 static specificdata_key_t veriexec_mountspecific_key;
    115 
    116 static LIST_HEAD(, veriexec_fpops) veriexec_fpops_list =
    117 	LIST_HEAD_INITIALIZER(veriexec_fpops_list);
    118 
    119 static int veriexec_raw_cb(kauth_cred_t, kauth_action_t, void *,
    120     void *, void *, void *, void *);
    121 static struct veriexec_fpops *veriexec_fpops_lookup(const char *);
    122 static void veriexec_file_free(struct veriexec_file_entry *);
    123 
    124 static unsigned int veriexec_tablecount = 0;
    125 
    126 /*
    127  * Veriexec operations global lock - most ops hold this as a read
    128  * lock, it is upgraded to a write lock when destroying veriexec file
    129  * table entries.
    130  */
    131 static krwlock_t veriexec_op_lock;
    132 
    133 /*
    134  * Sysctl helper routine for Veriexec.
    135  */
    136 static int
    137 sysctl_kern_veriexec_algorithms(SYSCTLFN_ARGS)
    138 {
    139 	size_t len;
    140 	int error;
    141 	const char *p;
    142 
    143 	if (newp != NULL)
    144 		return EPERM;
    145 
    146 	if (namelen != 0)
    147 		return EINVAL;
    148 
    149 	p = veriexec_fp_names == NULL ? "" : veriexec_fp_names;
    150 
    151 	len = strlen(p) + 1;
    152 
    153 	if (*oldlenp < len && oldp)
    154 		return ENOMEM;
    155 
    156 	if (oldp && (error = copyout(p, oldp, len)) != 0)
    157 		return error;
    158 
    159 	*oldlenp = len;
    160 	return 0;
    161 }
    162 
    163 static int
    164 sysctl_kern_veriexec_strict(SYSCTLFN_ARGS)
    165 {
    166 	struct sysctlnode node;
    167 	int error, newval;
    168 
    169 	node = *rnode;
    170 	node.sysctl_data = &newval;
    171 
    172 	newval = veriexec_strict;
    173 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    174 	if (error || newp == NULL)
    175 		return error;
    176 
    177 	if (newval < veriexec_strict)
    178 		return EPERM;
    179 
    180 	veriexec_strict = newval;
    181 
    182 	return 0;
    183 }
    184 
    185 SYSCTL_SETUP(sysctl_kern_veriexec_setup, "sysctl kern.veriexec setup")
    186 {
    187 	const struct sysctlnode *rnode = NULL;
    188 
    189 	sysctl_createv(clog, 0, NULL, &rnode,
    190 		       CTLFLAG_PERMANENT,
    191 		       CTLTYPE_NODE, "veriexec",
    192 		       SYSCTL_DESCR("Veriexec"),
    193 		       NULL, 0, NULL, 0,
    194 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    195 
    196 	sysctl_createv(clog, 0, &rnode, NULL,
    197 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    198 		       CTLTYPE_INT, "verbose",
    199 		       SYSCTL_DESCR("Veriexec verbose level"),
    200 		       NULL, 0, &veriexec_verbose, 0,
    201 		       CTL_CREATE, CTL_EOL);
    202 	sysctl_createv(clog, 0, &rnode, NULL,
    203 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    204 		       CTLTYPE_INT, "strict",
    205 		       SYSCTL_DESCR("Veriexec strict level"),
    206 		       sysctl_kern_veriexec_strict, 0, NULL, 0,
    207 		       CTL_CREATE, CTL_EOL);
    208 	sysctl_createv(clog, 0, &rnode, NULL,
    209 		       CTLFLAG_PERMANENT,
    210 		       CTLTYPE_STRING, "algorithms",
    211 		       SYSCTL_DESCR("Veriexec supported hashing "
    212 				    "algorithms"),
    213 		       sysctl_kern_veriexec_algorithms, 0, NULL, 0,
    214 		       CTL_CREATE, CTL_EOL);
    215 	sysctl_createv(clog, 0, &rnode, &veriexec_count_node,
    216 		       CTLFLAG_PERMANENT,
    217 		       CTLTYPE_NODE, "count",
    218 		       SYSCTL_DESCR("Number of fingerprints on mount(s)"),
    219 		       NULL, 0, NULL, 0,
    220 		       CTL_CREATE, CTL_EOL);
    221 }
    222 
    223 /*
    224  * Add ops to the fingerprint ops vector list.
    225  */
    226 int
    227 veriexec_fpops_add(const char *fp_type, size_t hash_len, size_t ctx_size,
    228     veriexec_fpop_init_t init, veriexec_fpop_update_t update,
    229     veriexec_fpop_final_t final)
    230 {
    231 	struct veriexec_fpops *ops;
    232 
    233 	KASSERT((init != NULL) && (update != NULL) && (final != NULL));
    234 	KASSERT((hash_len != 0) && (ctx_size != 0));
    235 	KASSERT(fp_type != NULL);
    236 
    237 	if (veriexec_fpops_lookup(fp_type) != NULL)
    238 		return (EEXIST);
    239 
    240 	ops = kmem_alloc(sizeof(*ops), KM_SLEEP);
    241 	ops->type = fp_type;
    242 	ops->hash_len = hash_len;
    243 	ops->context_size = ctx_size;
    244 	ops->init = init;
    245 	ops->update = update;
    246 	ops->final = final;
    247 
    248 	LIST_INSERT_HEAD(&veriexec_fpops_list, ops, entries);
    249 
    250 	/*
    251 	 * If we don't have space for any names, allocate enough for six
    252 	 * which should be sufficient. (it's also enough for all algorithms
    253 	 * we can support at the moment)
    254 	 */
    255 	if (veriexec_fp_names == NULL) {
    256 		veriexec_name_max = 64;
    257 		veriexec_fp_names = kmem_zalloc(veriexec_name_max, KM_SLEEP);
    258 	}
    259 
    260 	/*
    261 	 * If we're running out of space for storing supported algorithms,
    262 	 * extend the buffer with space for four names.
    263 	 */
    264 	while (veriexec_name_max - (strlen(veriexec_fp_names) + 1) <
    265 	    strlen(fp_type)) {
    266 		char *newp;
    267 		unsigned int new_max;
    268 
    269 		/* Add space for four algorithm names. */
    270 		new_max = veriexec_name_max + 64;
    271 		newp = kmem_zalloc(new_max, KM_SLEEP);
    272 		strlcpy(newp, veriexec_fp_names, new_max);
    273 		kmem_free(veriexec_fp_names, veriexec_name_max);
    274 		veriexec_fp_names = newp;
    275 		veriexec_name_max = new_max;
    276 	}
    277 
    278 	if (*veriexec_fp_names != '\0')
    279 		strlcat(veriexec_fp_names, " ", veriexec_name_max);
    280 
    281 	strlcat(veriexec_fp_names, fp_type, veriexec_name_max);
    282 
    283 	return (0);
    284 }
    285 
    286 static void
    287 veriexec_mountspecific_dtor(void *v)
    288 {
    289 	struct veriexec_table_entry *vte = v;
    290 
    291 	if (vte == NULL) {
    292 		return;
    293 	}
    294 	sysctl_free(__UNCONST(vte->vte_node));
    295 	veriexec_tablecount--;
    296 	kmem_free(vte, sizeof(*vte));
    297 }
    298 
    299 static int
    300 veriexec_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    301     void *arg0, void *arg1, void *arg2, void *arg3)
    302 {
    303 	int result;
    304 	enum kauth_system_req req;
    305 
    306 	if (action != KAUTH_SYSTEM_VERIEXEC)
    307 		return KAUTH_RESULT_DEFER;
    308 
    309 	result = KAUTH_RESULT_DEFER;
    310 	req = (enum kauth_system_req)(uintptr_t)arg0;
    311 
    312 	if (req == KAUTH_REQ_SYSTEM_VERIEXEC_MODIFY &&
    313 	    veriexec_strict > VERIEXEC_LEARNING) {
    314 		log(LOG_WARNING, "Veriexec: Strict mode, modifying "
    315 		    "tables not permitted.\n");
    316 
    317 		result = KAUTH_RESULT_DENY;
    318 	}
    319 
    320 	return result;
    321 }
    322 
    323 /*
    324  * Initialise Veriexec.
    325  */
    326 void
    327 veriexec_init(void)
    328 {
    329 	int error;
    330 
    331 	/* Register a fileassoc for Veriexec. */
    332 	error = fileassoc_register("veriexec",
    333 	    (fileassoc_cleanup_cb_t)veriexec_file_free, &veriexec_hook);
    334 	if (error)
    335 		panic("Veriexec: Can't register fileassoc: error=%d", error);
    336 
    337 	/* Register listener to handle raw disk access. */
    338 	if (kauth_listen_scope(KAUTH_SCOPE_DEVICE, veriexec_raw_cb, NULL) ==
    339 	    NULL)
    340 		panic("Veriexec: Can't listen on device scope");
    341 
    342 	error = mount_specific_key_create(&veriexec_mountspecific_key,
    343 	    veriexec_mountspecific_dtor);
    344 	if (error)
    345 		panic("Veriexec: Can't create mountspecific key");
    346 
    347 	if (kauth_listen_scope(KAUTH_SCOPE_SYSTEM, veriexec_listener_cb,
    348 	    NULL) == NULL)
    349 		panic("Veriexec: Can't listen on system scope");
    350 
    351 	rw_init(&veriexec_op_lock);
    352 
    353 #define	FPOPS_ADD(a, b, c, d, e, f)	\
    354 	veriexec_fpops_add(a, b, c, (veriexec_fpop_init_t)d, \
    355 	 (veriexec_fpop_update_t)e, (veriexec_fpop_final_t)f)
    356 
    357 #ifdef VERIFIED_EXEC_FP_SHA256
    358 	FPOPS_ADD("SHA256", SHA256_DIGEST_LENGTH, sizeof(SHA256_CTX),
    359 	    SHA256_Init, SHA256_Update, SHA256_Final);
    360 #endif /* VERIFIED_EXEC_FP_SHA256 */
    361 
    362 #ifdef VERIFIED_EXEC_FP_SHA384
    363 	FPOPS_ADD("SHA384", SHA384_DIGEST_LENGTH, sizeof(SHA384_CTX),
    364 	    SHA384_Init, SHA384_Update, SHA384_Final);
    365 #endif /* VERIFIED_EXEC_FP_SHA384 */
    366 
    367 #ifdef VERIFIED_EXEC_FP_SHA512
    368 	FPOPS_ADD("SHA512", SHA512_DIGEST_LENGTH, sizeof(SHA512_CTX),
    369 	    SHA512_Init, SHA512_Update, SHA512_Final);
    370 #endif /* VERIFIED_EXEC_FP_SHA512 */
    371 
    372 #undef FPOPS_ADD
    373 }
    374 
    375 static struct veriexec_fpops *
    376 veriexec_fpops_lookup(const char *name)
    377 {
    378 	struct veriexec_fpops *ops;
    379 
    380 	if (name == NULL)
    381 		return (NULL);
    382 
    383 	LIST_FOREACH(ops, &veriexec_fpops_list, entries) {
    384 		if (strcasecmp(name, ops->type) == 0)
    385 			return (ops);
    386 	}
    387 
    388 	return (NULL);
    389 }
    390 
    391 /*
    392  * Calculate fingerprint. Information on hash length and routines used is
    393  * extracted from veriexec_hash_list according to the hash type.
    394  *
    395  * NOTE: vfe is assumed to be locked for writing on entry.
    396  */
    397 static int
    398 veriexec_fp_calc(struct lwp *l, struct vnode *vp, int file_lock_state,
    399     struct veriexec_file_entry *vfe, u_char *fp)
    400 {
    401 	struct vattr va;
    402 	void *ctx;
    403 	u_char *buf;
    404 	off_t offset, len;
    405 	size_t resid;
    406 	int error;
    407 
    408 	KASSERT(file_lock_state != VERIEXEC_LOCKED);
    409 	KASSERT(file_lock_state != VERIEXEC_UNLOCKED);
    410 
    411 	if (file_lock_state == VERIEXEC_FILE_UNLOCKED)
    412 		vn_lock(vp, LK_SHARED | LK_RETRY);
    413 	error = VOP_GETATTR(vp, &va, l->l_cred);
    414 	if (file_lock_state == VERIEXEC_FILE_UNLOCKED)
    415 		VOP_UNLOCK(vp);
    416 	if (error)
    417 		return (error);
    418 
    419 	ctx = kmem_alloc(vfe->ops->context_size, KM_SLEEP);
    420 	buf = kmem_alloc(PAGE_SIZE, KM_SLEEP);
    421 
    422 	(vfe->ops->init)(ctx);
    423 
    424 	len = 0;
    425 	error = 0;
    426 	for (offset = 0; offset < va.va_size; offset += PAGE_SIZE) {
    427 		len = ((va.va_size - offset) < PAGE_SIZE) ?
    428 		    (va.va_size - offset) : PAGE_SIZE;
    429 
    430 		error = vn_rdwr(UIO_READ, vp, buf, len, offset,
    431 				UIO_SYSSPACE,
    432 				((file_lock_state == VERIEXEC_FILE_LOCKED)?
    433 				 IO_NODELOCKED : 0),
    434 				l->l_cred, &resid, NULL);
    435 
    436 		if (error) {
    437 			goto bad;
    438 		}
    439 
    440 		(vfe->ops->update)(ctx, buf, (unsigned int) len);
    441 
    442 		if (len != PAGE_SIZE)
    443 			break;
    444 	}
    445 
    446 	(vfe->ops->final)(fp, ctx);
    447 
    448 bad:
    449 	kmem_free(ctx, vfe->ops->context_size);
    450 	kmem_free(buf, PAGE_SIZE);
    451 
    452 	return (error);
    453 }
    454 
    455 /* Compare two fingerprints of the same type. */
    456 static int
    457 veriexec_fp_cmp(struct veriexec_fpops *ops, u_char *fp1, u_char *fp2)
    458 {
    459 	if (veriexec_verbose >= 2) {
    460 		int i;
    461 
    462 		printf("comparing hashes...\n");
    463 		printf("fp1: ");
    464 		for (i = 0; i < ops->hash_len; i++) {
    465 			printf("%02x", fp1[i]);
    466 		}
    467 		printf("\nfp2: ");
    468 		for (i = 0; i < ops->hash_len; i++) {
    469 			printf("%02x", fp2[i]);
    470 		}
    471 		printf("\n");
    472 	}
    473 
    474 	return (memcmp(fp1, fp2, ops->hash_len));
    475 }
    476 
    477 static int
    478 veriexec_fp_status(struct lwp *l, struct vnode *vp, int file_lock_state,
    479     struct veriexec_file_entry *vfe, u_char *status)
    480 {
    481 	size_t hash_len = vfe->ops->hash_len;
    482 	u_char *digest;
    483 	int error;
    484 
    485 	digest = kmem_zalloc(hash_len, KM_SLEEP);
    486 
    487 	error = veriexec_fp_calc(l, vp, file_lock_state, vfe, digest);
    488 	if (error)
    489 		goto out;
    490 
    491 	/* Compare fingerprint with loaded data. */
    492 	if (veriexec_fp_cmp(vfe->ops, vfe->fp, digest) == 0)
    493 		*status = FINGERPRINT_VALID;
    494 	else
    495 		*status = FINGERPRINT_NOMATCH;
    496 
    497 out:
    498 	kmem_free(digest, hash_len);
    499 	return error;
    500 }
    501 
    502 
    503 static struct veriexec_table_entry *
    504 veriexec_table_lookup(struct mount *mp)
    505 {
    506 	/* XXX: From raidframe init */
    507 	if (mp == NULL)
    508 		return NULL;
    509 
    510 	return mount_getspecific(mp, veriexec_mountspecific_key);
    511 }
    512 
    513 static struct veriexec_file_entry *
    514 veriexec_get(struct vnode *vp)
    515 {
    516 	return (fileassoc_lookup(vp, veriexec_hook));
    517 }
    518 
    519 bool
    520 veriexec_lookup(struct vnode *vp)
    521 {
    522 	return (veriexec_get(vp) == NULL ? false : true);
    523 }
    524 
    525 /*
    526  * Routine for maintaining mostly consistent message formats in Veriexec.
    527  */
    528 static void
    529 veriexec_file_report(struct veriexec_file_entry *vfe, const u_char *msg,
    530     const u_char *filename, struct lwp *l, int f)
    531 {
    532 	if (vfe != NULL && vfe->filename != NULL)
    533 		filename = vfe->filename;
    534 	if (filename == NULL)
    535 		return;
    536 
    537 	if (((f & REPORT_LOGMASK) >> 1) <= veriexec_verbose) {
    538 		if (!(f & REPORT_ALARM) || (l == NULL))
    539 			log(LOG_NOTICE, "Veriexec: %s [%s]\n", msg,
    540 			    filename);
    541 		else
    542 			log(LOG_ALERT, "Veriexec: %s [%s, prog=%s pid=%u, "
    543 			    "uid=%u, gid=%u]\n", msg, filename,
    544 			    l->l_proc->p_comm, l->l_proc->p_pid,
    545 			    kauth_cred_getuid(l->l_cred),
    546 			    kauth_cred_getgid(l->l_cred));
    547 	}
    548 
    549 	if (f & REPORT_PANIC)
    550 		panic("Veriexec: Unrecoverable error.");
    551 }
    552 
    553 /*
    554  * Verify the fingerprint of the given file. If we're called directly from
    555  * sys_execve(), 'flag' will be VERIEXEC_DIRECT. If we're called from
    556  * exec_script(), 'flag' will be VERIEXEC_INDIRECT.  If we are called from
    557  * vn_open(), 'flag' will be VERIEXEC_FILE.
    558  *
    559  * 'veriexec_op_lock' must be locked (and remains locked).
    560  *
    561  * NOTE: The veriexec file entry pointer (vfep) will be returned LOCKED
    562  *       on no error.
    563  */
    564 static int
    565 veriexec_file_verify(struct lwp *l, struct vnode *vp, const u_char *name,
    566     int flag, int file_lock_state, struct veriexec_file_entry **vfep)
    567 {
    568 	struct veriexec_file_entry *vfe;
    569 	int error = 0;
    570 
    571 	KASSERT(rw_lock_held(&veriexec_op_lock));
    572 	KASSERT(file_lock_state != VERIEXEC_LOCKED);
    573 	KASSERT(file_lock_state != VERIEXEC_UNLOCKED);
    574 
    575 #define VFE_NEEDS_EVAL(vfe) ((vfe->status == FINGERPRINT_NOTEVAL) || \
    576 			     (vfe->type & VERIEXEC_UNTRUSTED))
    577 
    578 	if (vfep != NULL)
    579 		*vfep = NULL;
    580 
    581 	if (vp->v_type != VREG)
    582 		return (0);
    583 
    584 	/* Lookup veriexec table entry, save pointer if requested. */
    585 	vfe = veriexec_get(vp);
    586 	if (vfep != NULL)
    587 		*vfep = vfe;
    588 
    589 	/* No entry in the veriexec tables. */
    590 	if (vfe == NULL) {
    591 		veriexec_file_report(NULL, "No entry.", name,
    592 		    l, REPORT_VERBOSE);
    593 
    594 		/*
    595 		 * Lockdown mode: Deny access to non-monitored files.
    596 		 * IPS mode: Deny execution of non-monitored files.
    597 		 */
    598 		if ((veriexec_strict >= VERIEXEC_LOCKDOWN) ||
    599 		    ((veriexec_strict >= VERIEXEC_IPS) &&
    600 		     (flag != VERIEXEC_FILE)))
    601 			return (EPERM);
    602 
    603 		return (0);
    604 	}
    605 
    606 	/*
    607 	 * Grab the lock for the entry, if we need to do an evaluation
    608 	 * then the lock is a write lock, after we have the write
    609 	 * lock, check if we really need it - some other thread may
    610 	 * have already done the work for us.
    611 	 */
    612 	if (VFE_NEEDS_EVAL(vfe)) {
    613 		rw_enter(&vfe->lock, RW_WRITER);
    614 		if (!VFE_NEEDS_EVAL(vfe))
    615 			rw_downgrade(&vfe->lock);
    616 	} else
    617 		rw_enter(&vfe->lock, RW_READER);
    618 
    619 	/* Evaluate fingerprint if needed. */
    620 	if (VFE_NEEDS_EVAL(vfe)) {
    621 		u_char status;
    622 
    623 		error = veriexec_fp_status(l, vp, file_lock_state, vfe, &status);
    624 		if (error) {
    625 			veriexec_file_report(vfe, "Fingerprint calculation error.",
    626 			    name, NULL, REPORT_ALWAYS);
    627 			rw_exit(&vfe->lock);
    628 			return (error);
    629 		}
    630 		vfe->status = status;
    631 		rw_downgrade(&vfe->lock);
    632 	}
    633 
    634 	if (!(vfe->type & flag)) {
    635 		veriexec_file_report(vfe, "Incorrect access type.", name, l,
    636 		    REPORT_ALWAYS|REPORT_ALARM);
    637 
    638 		/* IPS mode: Enforce access type. */
    639 		if (veriexec_strict >= VERIEXEC_IPS) {
    640 			rw_exit(&vfe->lock);
    641 			return (EPERM);
    642 		}
    643 	}
    644 
    645 	switch (vfe->status) {
    646 	case FINGERPRINT_NOTEVAL:
    647 		/* Should not happen. */
    648 		rw_exit(&vfe->lock);
    649 		veriexec_file_report(vfe, "Not-evaluated status "
    650 		    "post evaluation; inconsistency detected.", name,
    651 		    NULL, REPORT_ALWAYS|REPORT_PANIC);
    652 		__builtin_unreachable();
    653 		/* NOTREACHED */
    654 
    655 	case FINGERPRINT_VALID:
    656 		/* Valid fingerprint. */
    657 		veriexec_file_report(vfe, "Match.", name, NULL,
    658 		    REPORT_VERBOSE);
    659 
    660 		break;
    661 
    662 	case FINGERPRINT_NOMATCH:
    663 		/* Fingerprint mismatch. */
    664 		veriexec_file_report(vfe, "Mismatch.", name,
    665 		    NULL, REPORT_ALWAYS|REPORT_ALARM);
    666 
    667 		/* IDS mode: Deny access on fingerprint mismatch. */
    668 		if (veriexec_strict >= VERIEXEC_IDS) {
    669 			rw_exit(&vfe->lock);
    670 			error = EPERM;
    671 		}
    672 
    673 		break;
    674 
    675 	default:
    676 		/* Should never happen. */
    677 		rw_exit(&vfe->lock);
    678 		veriexec_file_report(vfe, "Invalid status "
    679 		    "post evaluation.", name, NULL, REPORT_ALWAYS|REPORT_PANIC);
    680 		/* NOTREACHED */
    681 	}
    682 
    683 	return (error);
    684 }
    685 
    686 int
    687 veriexec_verify(struct lwp *l, struct vnode *vp, const u_char *name, int flag,
    688     bool *found)
    689 {
    690 	struct veriexec_file_entry *vfe;
    691 	int r;
    692 
    693 	if (veriexec_bypass && (veriexec_strict == VERIEXEC_LEARNING))
    694 		return 0;
    695 
    696 	rw_enter(&veriexec_op_lock, RW_READER);
    697 	r = veriexec_file_verify(l, vp, name, flag, VERIEXEC_FILE_UNLOCKED,
    698 	    &vfe);
    699 	rw_exit(&veriexec_op_lock);
    700 
    701 	if ((r  == 0) && (vfe != NULL))
    702 		rw_exit(&vfe->lock);
    703 
    704 	if (found != NULL)
    705 		*found = (vfe != NULL) ? true : false;
    706 
    707 	return (r);
    708 }
    709 
    710 /*
    711  * Veriexec remove policy code.
    712  */
    713 int
    714 veriexec_removechk(struct lwp *l, struct vnode *vp, const char *pathbuf)
    715 {
    716 	struct veriexec_file_entry *vfe;
    717 	int error;
    718 
    719 	if (veriexec_bypass && (veriexec_strict == VERIEXEC_LEARNING))
    720 		return 0;
    721 
    722 	rw_enter(&veriexec_op_lock, RW_READER);
    723 	vfe = veriexec_get(vp);
    724 	rw_exit(&veriexec_op_lock);
    725 
    726 	if (vfe == NULL) {
    727 		/* Lockdown mode: Deny access to non-monitored files. */
    728 		if (veriexec_strict >= VERIEXEC_LOCKDOWN)
    729 			return (EPERM);
    730 
    731 		return (0);
    732 	}
    733 
    734 	veriexec_file_report(vfe, "Remove request.", pathbuf, l,
    735 	    REPORT_ALWAYS|REPORT_ALARM);
    736 
    737 	/* IDS mode: Deny removal of monitored files. */
    738 	if (veriexec_strict >= VERIEXEC_IDS)
    739 		error = EPERM;
    740 	else
    741 		error = veriexec_file_delete(l, vp);
    742 
    743 	return error;
    744 }
    745 
    746 /*
    747  * Veriexec rename policy.
    748  *
    749  * XXX: Once there's a way to hook after a successful rename, it would be
    750  * XXX: nice to update vfe->filename to the new name if it's not NULL and
    751  * XXX: the new name is absolute (ie., starts with a slash).
    752  */
    753 int
    754 veriexec_renamechk(struct lwp *l, struct vnode *fromvp, const char *fromname,
    755     struct vnode *tovp, const char *toname)
    756 {
    757 	struct veriexec_file_entry *fvfe = NULL, *tvfe = NULL;
    758 
    759 	if (veriexec_bypass && (veriexec_strict == VERIEXEC_LEARNING))
    760 		return 0;
    761 
    762 	rw_enter(&veriexec_op_lock, RW_READER);
    763 
    764 	if (veriexec_strict >= VERIEXEC_LOCKDOWN) {
    765 		log(LOG_ALERT, "Veriexec: Preventing rename of `%s' to "
    766 		    "`%s', uid=%u, pid=%u: Lockdown mode.\n", fromname, toname,
    767 		    kauth_cred_geteuid(l->l_cred), l->l_proc->p_pid);
    768 		rw_exit(&veriexec_op_lock);
    769 		return (EPERM);
    770 	}
    771 
    772 	fvfe = veriexec_get(fromvp);
    773 	if (tovp != NULL)
    774 		tvfe = veriexec_get(tovp);
    775 
    776 	if ((fvfe == NULL) && (tvfe == NULL)) {
    777 		/* None of them is monitored */
    778 		rw_exit(&veriexec_op_lock);
    779 		return 0;
    780 	}
    781 
    782 	if (veriexec_strict >= VERIEXEC_IPS) {
    783 		log(LOG_ALERT, "Veriexec: Preventing rename of `%s' "
    784 		    "to `%s', uid=%u, pid=%u: IPS mode, %s "
    785 		    "monitored.\n", fromname, toname,
    786 		    kauth_cred_geteuid(l->l_cred),
    787 		    l->l_proc->p_pid, (fvfe != NULL && tvfe != NULL) ?
    788 		    "files" : "file");
    789 		rw_exit(&veriexec_op_lock);
    790 		return (EPERM);
    791 	}
    792 
    793 	if (fvfe != NULL) {
    794 		/*
    795 		 * Monitored file is renamed; filename no longer relevant.
    796 		 */
    797 
    798 		/*
    799 		 * XXX: We could keep the buffer, and when (and if) updating the
    800 		 * XXX: filename post-rename, re-allocate it only if it's not
    801 		 * XXX: big enough for the new filename.
    802 		 */
    803 
    804 		/* XXX: Get write lock on fvfe here? */
    805 
    806 		VERIEXEC_RW_UPGRADE(&veriexec_op_lock);
    807 		/* once we have the op lock in write mode
    808 		 * there should be no locks on any file
    809 		 * entries so we can destroy the object.
    810 		 */
    811 
    812 		if (fvfe->filename_len > 0)
    813 			kmem_free(fvfe->filename, fvfe->filename_len);
    814 
    815 		fvfe->filename = NULL;
    816 		fvfe->filename_len = 0;
    817 
    818 		rw_downgrade(&veriexec_op_lock);
    819 	}
    820 
    821 	log(LOG_NOTICE, "Veriexec: %s file `%s' renamed to "
    822 	    "%s file `%s', uid=%u, pid=%u.\n", (fvfe != NULL) ?
    823 	    "Monitored" : "Non-monitored", fromname, (tvfe != NULL) ?
    824 	    "monitored" : "non-monitored", toname,
    825 	    kauth_cred_geteuid(l->l_cred), l->l_proc->p_pid);
    826 
    827 	rw_exit(&veriexec_op_lock);
    828 
    829 	if (tvfe != NULL) {
    830 		/*
    831 		 * Monitored file is overwritten. Remove the entry.
    832 		 */
    833 		(void)veriexec_file_delete(l, tovp);
    834 	}
    835 
    836 	return (0);
    837 }
    838 
    839 static void
    840 veriexec_file_free(struct veriexec_file_entry *vfe)
    841 {
    842 	if (vfe != NULL) {
    843 		if (vfe->fp != NULL)
    844 			kmem_free(vfe->fp, vfe->ops->hash_len);
    845 		if (vfe->filename != NULL)
    846 			kmem_free(vfe->filename, vfe->filename_len);
    847 		rw_destroy(&vfe->lock);
    848 		kmem_free(vfe, sizeof(*vfe));
    849 	}
    850 }
    851 
    852 static void
    853 veriexec_file_purge(struct veriexec_file_entry *vfe, int have_lock)
    854 {
    855 	if (vfe == NULL)
    856 		return;
    857 
    858 	if (have_lock == VERIEXEC_UNLOCKED)
    859 		rw_enter(&vfe->lock, RW_WRITER);
    860 	else
    861 		VERIEXEC_RW_UPGRADE(&vfe->lock);
    862 
    863 	vfe->status = FINGERPRINT_NOTEVAL;
    864 	if (have_lock == VERIEXEC_UNLOCKED)
    865 		rw_exit(&vfe->lock);
    866 	else
    867 		rw_downgrade(&vfe->lock);
    868 }
    869 
    870 static void
    871 veriexec_file_purge_cb(struct veriexec_file_entry *vfe, void *cookie)
    872 {
    873 	veriexec_file_purge(vfe, VERIEXEC_UNLOCKED);
    874 }
    875 
    876 /*
    877  * Invalidate a Veriexec file entry.
    878  * XXX: This should be updated when per-page fingerprints are added.
    879  */
    880 void
    881 veriexec_purge(struct vnode *vp)
    882 {
    883 	rw_enter(&veriexec_op_lock, RW_READER);
    884 	veriexec_file_purge(veriexec_get(vp), VERIEXEC_UNLOCKED);
    885 	rw_exit(&veriexec_op_lock);
    886 }
    887 
    888 /*
    889  * Enforce raw disk access policy.
    890  *
    891  * IDS mode: Invalidate fingerprints on a mount if it's opened for writing.
    892  * IPS mode: Don't allow raw writing to disks we monitor.
    893  * Lockdown mode: Don't allow raw writing to all disks.
    894  *
    895  * XXX: This is bogus. There's an obvious race condition between the time
    896  * XXX: the disk is open for writing, in which an attacker can access a
    897  * XXX: monitored file to get its signature cached again, and when the raw
    898  * XXX: file is overwritten on disk.
    899  * XXX:
    900  * XXX: To solve this, we need something like the following:
    901  * XXX:		open raw disk:
    902  * XXX:		  - raise refcount,
    903  * XXX:		  - invalidate fingerprints,
    904  * XXX:		  - mark all entries for that disk with "no cache" flag
    905  * XXX:
    906  * XXX:		veriexec_verify:
    907  * XXX:		  - if "no cache", don't cache evaluation result
    908  * XXX:
    909  * XXX:		close raw disk:
    910  * XXX:		  - lower refcount,
    911  * XXX:		  - if refcount == 0, remove "no cache" flag from all entries
    912  */
    913 static int
    914 veriexec_raw_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    915     void *arg0, void *arg1, void *arg2, void *arg3)
    916 {
    917 	int result;
    918 	enum kauth_device_req req;
    919 	struct veriexec_table_entry *vte;
    920 
    921 	result = KAUTH_RESULT_DENY;
    922 	req = (enum kauth_device_req)(uintptr_t)arg0;
    923 
    924 	switch (action) {
    925 	case KAUTH_DEVICE_RAWIO_SPEC: {
    926 		struct vnode *vp, *bvp;
    927 		int error;
    928 
    929 		if (req == KAUTH_REQ_DEVICE_RAWIO_SPEC_READ) {
    930 			result = KAUTH_RESULT_DEFER;
    931 			break;
    932 		}
    933 
    934 		vp = arg1;
    935 		KASSERT(vp != NULL);
    936 
    937 		/* Handle /dev/mem and /dev/kmem. */
    938 		if (iskmemvp(vp)) {
    939 			if (veriexec_strict < VERIEXEC_IPS)
    940 				result = KAUTH_RESULT_DEFER;
    941 
    942 			break;
    943 		}
    944 
    945 		error = rawdev_mounted(vp, &bvp);
    946 		if (error == EINVAL) {
    947 			result = KAUTH_RESULT_DEFER;
    948 			break;
    949 		}
    950 
    951 		/*
    952 		 * XXX: See vfs_mountedon() comment in rawdev_mounted().
    953 		 */
    954 		vte = veriexec_table_lookup(bvp->v_mount);
    955 		if (vte == NULL) {
    956 			result = KAUTH_RESULT_DEFER;
    957 			break;
    958 		}
    959 
    960 		switch (veriexec_strict) {
    961 		case VERIEXEC_LEARNING:
    962 		case VERIEXEC_IDS:
    963 			result = KAUTH_RESULT_DEFER;
    964 
    965 			rw_enter(&veriexec_op_lock, RW_WRITER);
    966 			fileassoc_table_run(bvp->v_mount, veriexec_hook,
    967 			    (fileassoc_cb_t)veriexec_file_purge_cb, NULL);
    968 			rw_exit(&veriexec_op_lock);
    969 
    970 			break;
    971 		case VERIEXEC_IPS:
    972 			result = KAUTH_RESULT_DENY;
    973 			break;
    974 		case VERIEXEC_LOCKDOWN:
    975 			result = KAUTH_RESULT_DENY;
    976 			break;
    977 		}
    978 
    979 		break;
    980 		}
    981 
    982 	case KAUTH_DEVICE_RAWIO_PASSTHRU:
    983 		/* XXX What can we do here? */
    984 		if (veriexec_strict < VERIEXEC_IPS)
    985 			result = KAUTH_RESULT_DEFER;
    986 
    987 		break;
    988 
    989 	default:
    990 		result = KAUTH_RESULT_DEFER;
    991 		break;
    992 	}
    993 
    994 	return (result);
    995 }
    996 
    997 /*
    998  * Create a new Veriexec table.
    999  */
   1000 static struct veriexec_table_entry *
   1001 veriexec_table_add(struct lwp *l, struct mount *mp)
   1002 {
   1003 	struct veriexec_table_entry *vte;
   1004 	u_char buf[16];
   1005 
   1006 	vte = kmem_zalloc(sizeof(*vte), KM_SLEEP);
   1007 	mount_setspecific(mp, veriexec_mountspecific_key, vte);
   1008 
   1009 	snprintf(buf, sizeof(buf), "table%u", veriexec_tablecount++);
   1010 	sysctl_createv(NULL, 0, &veriexec_count_node, &vte->vte_node,
   1011 		       0, CTLTYPE_NODE, buf, NULL, NULL, 0, NULL,
   1012 		       0, CTL_CREATE, CTL_EOL);
   1013 
   1014 	sysctl_createv(NULL, 0, &vte->vte_node, NULL,
   1015 		       CTLFLAG_READONLY, CTLTYPE_STRING, "mntpt",
   1016 		       NULL, NULL, 0, mp->mnt_stat.f_mntonname,
   1017 		       0, CTL_CREATE, CTL_EOL);
   1018 	sysctl_createv(NULL, 0, &vte->vte_node, NULL,
   1019 		       CTLFLAG_READONLY, CTLTYPE_STRING, "fstype",
   1020 		       NULL, NULL, 0, mp->mnt_stat.f_fstypename,
   1021 		       0, CTL_CREATE, CTL_EOL);
   1022 	sysctl_createv(NULL, 0, &vte->vte_node, NULL,
   1023 		       CTLFLAG_READONLY, CTLTYPE_QUAD, "nentries",
   1024 		       NULL, NULL, 0, &vte->vte_count, 0, CTL_CREATE, CTL_EOL);
   1025 
   1026 	return (vte);
   1027 }
   1028 
   1029 /*
   1030  * Add a file to be monitored by Veriexec.
   1031  *
   1032  * Expected elements in dict:
   1033  *     file, fp, fp-type, entry-type, keep-filename, eval-on-load.
   1034  */
   1035 int
   1036 veriexec_file_add(struct lwp *l, prop_dictionary_t dict)
   1037 {
   1038 	struct veriexec_table_entry *vte;
   1039 	struct veriexec_file_entry *vfe = NULL;
   1040 	struct veriexec_file_entry *ovfe;
   1041 	struct vnode *vp;
   1042 	const char *file, *fp_type;
   1043 	int error;
   1044 	bool ignore_dup = false;
   1045 
   1046 	if (!prop_dictionary_get_cstring_nocopy(dict, "file", &file))
   1047 		return (EINVAL);
   1048 
   1049 	error = namei_simple_kernel(file, NSM_FOLLOW_NOEMULROOT, &vp);
   1050 	if (error)
   1051 		return (error);
   1052 
   1053 	/* Add only regular files. */
   1054 	if (vp->v_type != VREG) {
   1055 		log(LOG_ERR, "Veriexec: Not adding `%s': Not a regular file.\n",
   1056 		    file);
   1057 		error = EBADF;
   1058 		goto out;
   1059 	}
   1060 
   1061 	vfe = kmem_zalloc(sizeof(*vfe), KM_SLEEP);
   1062 	rw_init(&vfe->lock);
   1063 
   1064 	/* Lookup fingerprint hashing algorithm. */
   1065 	fp_type = prop_string_cstring_nocopy(prop_dictionary_get(dict,
   1066 	    "fp-type"));
   1067 	if ((vfe->ops = veriexec_fpops_lookup(fp_type)) == NULL) {
   1068 		log(LOG_ERR, "Veriexec: Invalid or unknown fingerprint type "
   1069 		    "`%s' for file `%s'.\n", fp_type, file);
   1070 		error = EOPNOTSUPP;
   1071 		goto out;
   1072 	}
   1073 
   1074 	if (prop_data_size(prop_dictionary_get(dict, "fp")) !=
   1075 	    vfe->ops->hash_len) {
   1076 		log(LOG_ERR, "Veriexec: Bad fingerprint length for `%s'.\n",
   1077 		    file);
   1078 		error = EINVAL;
   1079 		goto out;
   1080 	}
   1081 
   1082 	vfe->fp = kmem_alloc(vfe->ops->hash_len, KM_SLEEP);
   1083 	memcpy(vfe->fp, prop_data_data_nocopy(prop_dictionary_get(dict, "fp")),
   1084 	    vfe->ops->hash_len);
   1085 
   1086 	rw_enter(&veriexec_op_lock, RW_WRITER);
   1087 
   1088 	/* Continue entry initialization. */
   1089 	if (prop_dictionary_get_uint8(dict, "entry-type", &vfe->type) == FALSE)
   1090 		vfe->type = 0;
   1091 	else {
   1092 		uint8_t extra_flags;
   1093 
   1094 		extra_flags = vfe->type & ~(VERIEXEC_DIRECT |
   1095 		    VERIEXEC_INDIRECT | VERIEXEC_FILE | VERIEXEC_UNTRUSTED);
   1096 		if (extra_flags) {
   1097 			log(LOG_NOTICE, "Veriexec: Contaminated flags `0x%x' "
   1098 			    "for `%s', skipping.\n", extra_flags, file);
   1099 			error = EINVAL;
   1100 			goto unlock_out;
   1101 		}
   1102 	}
   1103 	if (!(vfe->type & (VERIEXEC_DIRECT | VERIEXEC_INDIRECT |
   1104 	    VERIEXEC_FILE)))
   1105 		vfe->type |= VERIEXEC_DIRECT;
   1106 
   1107 	vfe->status = FINGERPRINT_NOTEVAL;
   1108 	if (prop_bool_true(prop_dictionary_get(dict, "keep-filename"))) {
   1109 		vfe->filename = kmem_strdupsize(file, &vfe->filename_len,
   1110 		    KM_SLEEP);
   1111 	} else
   1112 		vfe->filename = NULL;
   1113 
   1114 	if (prop_bool_true(prop_dictionary_get(dict, "eval-on-load")) ||
   1115 	    (vfe->type & VERIEXEC_UNTRUSTED)) {
   1116 		u_char status;
   1117 
   1118 		error = veriexec_fp_status(l, vp, VERIEXEC_FILE_UNLOCKED,
   1119 		    vfe, &status);
   1120 		if (error)
   1121 			goto unlock_out;
   1122 		vfe->status = status;
   1123 	}
   1124 
   1125 	/*
   1126 	 * If we already have an entry for this file, and it matches
   1127 	 * the new entry exactly (except for the filename, which may
   1128 	 * hard-linked!), we just ignore the new entry.  If the new
   1129 	 * entry differs, report the error.
   1130 	 */
   1131 	if ((ovfe = veriexec_get(vp)) != NULL) {
   1132 		error = EEXIST;
   1133 		if (vfe->type == ovfe->type &&
   1134 		    vfe->status == ovfe->status &&
   1135 		    vfe->ops == ovfe->ops &&
   1136 		    memcmp(vfe->fp, ovfe->fp, vfe->ops->hash_len) == 0)
   1137 			ignore_dup = true;
   1138 		goto unlock_out;
   1139 	}
   1140 
   1141 	vte = veriexec_table_lookup(vp->v_mount);
   1142 	if (vte == NULL)
   1143 		vte = veriexec_table_add(l, vp->v_mount);
   1144 
   1145 	/* XXX if we bail below this, we might want to gc newly created vtes. */
   1146 
   1147 	error = fileassoc_add(vp, veriexec_hook, vfe);
   1148 	if (error)
   1149 		goto unlock_out;
   1150 
   1151 	vte->vte_count++;
   1152 
   1153 	veriexec_file_report(NULL, "New entry.", file, NULL, REPORT_DEBUG);
   1154 	veriexec_bypass = 0;
   1155 
   1156   unlock_out:
   1157 	rw_exit(&veriexec_op_lock);
   1158 
   1159   out:
   1160 	vrele(vp);
   1161 	if (error)
   1162 		veriexec_file_free(vfe);
   1163 
   1164 	if (ignore_dup && error == EEXIST)
   1165 		error = 0;
   1166 
   1167 	return (error);
   1168 }
   1169 
   1170 int
   1171 veriexec_table_delete(struct lwp *l, struct mount *mp)
   1172 {
   1173 	struct veriexec_table_entry *vte;
   1174 
   1175 	vte = veriexec_table_lookup(mp);
   1176 	if (vte == NULL)
   1177 		return (ENOENT);
   1178 
   1179 	veriexec_mountspecific_dtor(vte);
   1180 	mount_setspecific(mp, veriexec_mountspecific_key, NULL);
   1181 
   1182 	return (fileassoc_table_clear(mp, veriexec_hook));
   1183 }
   1184 
   1185 int
   1186 veriexec_file_delete(struct lwp *l, struct vnode *vp)
   1187 {
   1188 	struct veriexec_table_entry *vte;
   1189 	int error;
   1190 
   1191 	vte = veriexec_table_lookup(vp->v_mount);
   1192 	if (vte == NULL)
   1193 		return (ENOENT);
   1194 
   1195 	rw_enter(&veriexec_op_lock, RW_WRITER);
   1196 	error = fileassoc_clear(vp, veriexec_hook);
   1197 	rw_exit(&veriexec_op_lock);
   1198 	if (!error) {
   1199 		KASSERT(vte->vte_count > 0);
   1200 		vte->vte_count--;
   1201 	}
   1202 
   1203 	return (error);
   1204 }
   1205 
   1206 /*
   1207  * Convert Veriexec entry data to a dictionary readable by userland tools.
   1208  */
   1209 static void
   1210 veriexec_file_convert(struct veriexec_file_entry *vfe, prop_dictionary_t rdict)
   1211 {
   1212 	if (vfe->filename)
   1213 		prop_dictionary_set(rdict, "file",
   1214 		    prop_string_create_cstring(vfe->filename));
   1215 	prop_dictionary_set_uint8(rdict, "entry-type", vfe->type);
   1216 	prop_dictionary_set_uint8(rdict, "status", vfe->status);
   1217 	prop_dictionary_set(rdict, "fp-type",
   1218 	    prop_string_create_cstring(vfe->ops->type));
   1219 	prop_dictionary_set(rdict, "fp",
   1220 	    prop_data_create_data(vfe->fp, vfe->ops->hash_len));
   1221 }
   1222 
   1223 int
   1224 veriexec_convert(struct vnode *vp, prop_dictionary_t rdict)
   1225 {
   1226 	struct veriexec_file_entry *vfe;
   1227 
   1228 	rw_enter(&veriexec_op_lock, RW_READER);
   1229 
   1230 	vfe = veriexec_get(vp);
   1231 	if (vfe == NULL) {
   1232 		rw_exit(&veriexec_op_lock);
   1233 		return (ENOENT);
   1234 	}
   1235 
   1236 	rw_enter(&vfe->lock, RW_READER);
   1237 	veriexec_file_convert(vfe, rdict);
   1238 	rw_exit(&vfe->lock);
   1239 
   1240 	rw_exit(&veriexec_op_lock);
   1241 	return (0);
   1242 }
   1243 
   1244 int
   1245 veriexec_unmountchk(struct mount *mp)
   1246 {
   1247 	int error;
   1248 
   1249 	if ((veriexec_bypass && (veriexec_strict == VERIEXEC_LEARNING))
   1250 	    || doing_shutdown)
   1251 		return (0);
   1252 
   1253 	rw_enter(&veriexec_op_lock, RW_READER);
   1254 
   1255 	switch (veriexec_strict) {
   1256 	case VERIEXEC_LEARNING:
   1257 		error = 0;
   1258 		break;
   1259 
   1260 	case VERIEXEC_IDS:
   1261 		if (veriexec_table_lookup(mp) != NULL) {
   1262 			log(LOG_INFO, "Veriexec: IDS mode, allowing unmount "
   1263 			    "of \"%s\".\n", mp->mnt_stat.f_mntonname);
   1264 		}
   1265 
   1266 		error = 0;
   1267 		break;
   1268 
   1269 	case VERIEXEC_IPS: {
   1270 		struct veriexec_table_entry *vte;
   1271 
   1272 		vte = veriexec_table_lookup(mp);
   1273 		if ((vte != NULL) && (vte->vte_count > 0)) {
   1274 			log(LOG_ALERT, "Veriexec: IPS mode, preventing"
   1275 			    " unmount of \"%s\" with monitored files.\n",
   1276 			    mp->mnt_stat.f_mntonname);
   1277 
   1278 			error = EPERM;
   1279 		} else
   1280 			error = 0;
   1281 		break;
   1282 		}
   1283 
   1284 	case VERIEXEC_LOCKDOWN:
   1285 	default:
   1286 		log(LOG_ALERT, "Veriexec: Lockdown mode, preventing unmount "
   1287 		    "of \"%s\".\n", mp->mnt_stat.f_mntonname);
   1288 		error = EPERM;
   1289 		break;
   1290 	}
   1291 
   1292 	rw_exit(&veriexec_op_lock);
   1293 	return (error);
   1294 }
   1295 
   1296 int
   1297 veriexec_openchk(struct lwp *l, struct vnode *vp, const char *path, int fmode)
   1298 {
   1299 	struct veriexec_file_entry *vfe = NULL;
   1300 	int error = 0;
   1301 
   1302 	if (veriexec_bypass && (veriexec_strict == VERIEXEC_LEARNING))
   1303 		return 0;
   1304 
   1305 	if (vp == NULL) {
   1306 		/* If no creation requested, let this fail normally. */
   1307 		if (!(fmode & O_CREAT))
   1308 			goto out;
   1309 
   1310 		/* Lockdown mode: Prevent creation of new files. */
   1311 		if (veriexec_strict >= VERIEXEC_LOCKDOWN) {
   1312 			log(LOG_ALERT, "Veriexec: Preventing new file "
   1313 			    "creation in `%s'.\n", path);
   1314 			error = EPERM;
   1315 		}
   1316 
   1317 		goto out;
   1318 	}
   1319 
   1320 	rw_enter(&veriexec_op_lock, RW_READER);
   1321 	error = veriexec_file_verify(l, vp, path, VERIEXEC_FILE,
   1322 				     VERIEXEC_FILE_LOCKED, &vfe);
   1323 
   1324 	if (error) {
   1325 		rw_exit(&veriexec_op_lock);
   1326 		goto out;
   1327 	}
   1328 
   1329 	if ((vfe != NULL) && ((fmode & FWRITE) || (fmode & O_TRUNC))) {
   1330 		veriexec_file_report(vfe, "Write access request.", path, l,
   1331 		    REPORT_ALWAYS | REPORT_ALARM);
   1332 
   1333 		/* IPS mode: Deny write access to monitored files. */
   1334 		if (veriexec_strict >= VERIEXEC_IPS)
   1335 			error = EPERM;
   1336 		else
   1337 			veriexec_file_purge(vfe, VERIEXEC_LOCKED);
   1338 	}
   1339 
   1340 	if (vfe != NULL)
   1341 		rw_exit(&vfe->lock);
   1342 
   1343 	rw_exit(&veriexec_op_lock);
   1344  out:
   1345 	return (error);
   1346 }
   1347 
   1348 static void
   1349 veriexec_file_dump(struct veriexec_file_entry *vfe, prop_array_t entries)
   1350 {
   1351 	prop_dictionary_t entry;
   1352 
   1353 	/* If we don't have a filename, this is meaningless. */
   1354 	if (vfe->filename == NULL)
   1355 		return;
   1356 
   1357 	entry = prop_dictionary_create();
   1358 
   1359 	veriexec_file_convert(vfe, entry);
   1360 
   1361 	prop_array_add(entries, entry);
   1362 }
   1363 
   1364 int
   1365 veriexec_dump(struct lwp *l, prop_array_t rarray)
   1366 {
   1367 	mount_iterator_t *iter;
   1368 	struct mount *mp;
   1369 
   1370 	mountlist_iterator_init(&iter);
   1371 	while ((mp = mountlist_iterator_next(iter)) != NULL) {
   1372 		fileassoc_table_run(mp, veriexec_hook,
   1373 		    (fileassoc_cb_t)veriexec_file_dump, rarray);
   1374 	}
   1375 	mountlist_iterator_destroy(iter);
   1376 
   1377 	return (0);
   1378 }
   1379 
   1380 int
   1381 veriexec_flush(struct lwp *l)
   1382 {
   1383 	mount_iterator_t *iter;
   1384 	struct mount *mp;
   1385 	int error = 0;
   1386 
   1387 	mountlist_iterator_init(&iter);
   1388 	while ((mp = mountlist_iterator_next(iter)) != NULL) {
   1389 		int lerror;
   1390 
   1391 		lerror = veriexec_table_delete(l, mp);
   1392 		if (lerror && lerror != ENOENT)
   1393 			error = lerror;
   1394 	}
   1395 	mountlist_iterator_destroy(iter);
   1396 
   1397 	return (error);
   1398 }
   1399