xref: /freebsd/usr.sbin/jail/command.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
1 /*-
2  * Copyright (c) 2011 James Gritton
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/types.h>
31 #include <sys/event.h>
32 #include <sys/mount.h>
33 #include <sys/stat.h>
34 #include <sys/sysctl.h>
35 #include <sys/user.h>
36 #include <sys/wait.h>
37 
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <kvm.h>
42 #include <login_cap.h>
43 #include <paths.h>
44 #include <pwd.h>
45 #include <signal.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "jailp.h"
52 
53 #define DEFAULT_STOP_TIMEOUT	10
54 #define PHASH_SIZE		256
55 
56 LIST_HEAD(phhead, phash);
57 
58 struct phash {
59 	LIST_ENTRY(phash)	le;
60 	struct cfjail		*j;
61 	pid_t			pid;
62 };
63 
64 int paralimit = -1;
65 
66 extern char **environ;
67 
68 static int run_command(struct cfjail *j);
69 static void add_proc(struct cfjail *j, pid_t pid);
70 static void clear_procs(struct cfjail *j);
71 static struct cfjail *find_proc(pid_t pid);
72 static int term_procs(struct cfjail *j);
73 static int get_user_info(struct cfjail *j, const char *username,
74     const struct passwd **pwdp, login_cap_t **lcapp);
75 static int check_path(struct cfjail *j, const char *pname, const char *path,
76     int isfile, const char *umount_type);
77 
78 static struct cfjails sleeping = TAILQ_HEAD_INITIALIZER(sleeping);
79 static struct cfjails runnable = TAILQ_HEAD_INITIALIZER(runnable);
80 static struct cfstring dummystring = { .len = 1 };
81 static struct phhead phash[PHASH_SIZE];
82 static int kq;
83 
84 /*
85  * Run the next command associated with a jail.
86  */
87 int
88 next_command(struct cfjail *j)
89 {
90 	enum intparam comparam;
91 	int create_failed;
92 
93 	if (paralimit == 0) {
94 		requeue(j, &runnable);
95 		return 1;
96 	}
97 	create_failed = (j->flags & (JF_STOP | JF_FAILED)) == JF_FAILED;
98 	comparam = *j->comparam;
99 	for (;;) {
100 		if (j->comstring == NULL) {
101 			j->comparam += create_failed ? -1 : 1;
102 			switch ((comparam = *j->comparam)) {
103 			case IP__NULL:
104 				return 0;
105 			case IP_MOUNT_DEVFS:
106 				if (!bool_param(j->intparams[IP_MOUNT_DEVFS]))
107 					continue;
108 				/* FALLTHROUGH */
109 			case IP__OP:
110 			case IP_STOP_TIMEOUT:
111 				j->comstring = &dummystring;
112 				break;
113 			default:
114 				if (j->intparams[comparam] == NULL)
115 					continue;
116 				j->comstring = create_failed
117 				    ? TAILQ_LAST(&j->intparams[comparam]->val,
118 					cfstrings)
119 				    : TAILQ_FIRST(&j->intparams[comparam]->val);
120 			}
121 		} else {
122 			j->comstring = j->comstring == &dummystring ? NULL :
123 			    create_failed
124 			    ? TAILQ_PREV(j->comstring, cfstrings, tq)
125 			    : TAILQ_NEXT(j->comstring, tq);
126 		}
127 		if (j->comstring == NULL || j->comstring->len == 0 ||
128 		    (create_failed && (comparam == IP_EXEC_PRESTART ||
129 		    comparam == IP_EXEC_START || comparam == IP_COMMAND ||
130 		    comparam == IP_EXEC_POSTSTART)))
131 			continue;
132 		switch (run_command(j)) {
133 		case -1:
134 			failed(j);
135 			/* FALLTHROUGH */
136 		case 1:
137 			return 1;
138 		}
139 	}
140 }
141 
142 /*
143  * Check command exit status
144  */
145 int
146 finish_command(struct cfjail *j)
147 {
148 	int error;
149 
150 	if (!(j->flags & JF_SLEEPQ))
151 		return 0;
152 	j->flags &= ~JF_SLEEPQ;
153 	if (*j->comparam == IP_STOP_TIMEOUT)
154 	{
155 		j->flags &= ~JF_TIMEOUT;
156 		j->pstatus = 0;
157 		return 0;
158 	}
159 	paralimit++;
160 	if (!TAILQ_EMPTY(&runnable))
161 		requeue(TAILQ_FIRST(&runnable), &ready);
162 	error = 0;
163 	if (j->flags & JF_TIMEOUT) {
164 		j->flags &= ~JF_TIMEOUT;
165 		if (*j->comparam != IP_STOP_TIMEOUT) {
166 			jail_warnx(j, "%s: timed out", j->comline);
167 			failed(j);
168 			error = -1;
169 		} else if (verbose > 0)
170 			jail_note(j, "timed out\n");
171 	} else if (j->pstatus != 0) {
172 		if (WIFSIGNALED(j->pstatus))
173 			jail_warnx(j, "%s: exited on signal %d",
174 			    j->comline, WTERMSIG(j->pstatus));
175 		else
176 			jail_warnx(j, "%s: failed", j->comline);
177 		j->pstatus = 0;
178 		failed(j);
179 		error = -1;
180 	}
181 	free(j->comline);
182 	j->comline = NULL;
183 	return error;
184 }
185 
186 /*
187  * Check for finished processes or timeouts.
188  */
189 struct cfjail *
190 next_proc(int nonblock)
191 {
192 	struct kevent ke;
193 	struct timespec ts;
194 	struct timespec *tsp;
195 	struct cfjail *j;
196 
197 	if (!TAILQ_EMPTY(&sleeping)) {
198 	again:
199 		tsp = NULL;
200 		if ((j = TAILQ_FIRST(&sleeping)) && j->timeout.tv_sec) {
201 			clock_gettime(CLOCK_REALTIME, &ts);
202 			ts.tv_sec = j->timeout.tv_sec - ts.tv_sec;
203 			ts.tv_nsec = j->timeout.tv_nsec - ts.tv_nsec;
204 			if (ts.tv_nsec < 0) {
205 				ts.tv_sec--;
206 				ts.tv_nsec += 1000000000;
207 			}
208 			if (ts.tv_sec < 0 ||
209 			    (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
210 				j->flags |= JF_TIMEOUT;
211 				clear_procs(j);
212 				return j;
213 			}
214 			tsp = &ts;
215 		}
216 		if (nonblock) {
217 			ts.tv_sec = 0;
218 			ts.tv_nsec = 0;
219 			tsp = &ts;
220 		}
221 		switch (kevent(kq, NULL, 0, &ke, 1, tsp)) {
222 		case -1:
223 			if (errno != EINTR)
224 				err(1, "kevent");
225 			goto again;
226 		case 0:
227 			if (!nonblock) {
228 				j = TAILQ_FIRST(&sleeping);
229 				j->flags |= JF_TIMEOUT;
230 				clear_procs(j);
231 				return j;
232 			}
233 			break;
234 		case 1:
235 			(void)waitpid(ke.ident, NULL, WNOHANG);
236 			if ((j = find_proc(ke.ident))) {
237 				j->pstatus = ke.data;
238 				return j;
239 			}
240 			goto again;
241 		}
242 	}
243 	return NULL;
244 }
245 
246 /*
247  * Run a single command for a jail, possible inside the jail.
248  */
249 static int
250 run_command(struct cfjail *j)
251 {
252 	const struct passwd *pwd;
253 	const struct cfstring *comstring, *s;
254 	login_cap_t *lcap;
255 	char **argv;
256 	char *cs, *comcs, *devpath;
257 	const char *jidstr, *conslog, *path, *ruleset, *term, *username;
258 	enum intparam comparam;
259 	size_t comlen;
260 	pid_t pid;
261 	int argc, bg, clean, consfd, down, fib, i, injail, sjuser, timeout;
262 #if defined(INET) || defined(INET6)
263 	char *addr;
264 #endif
265 
266 	static char *cleanenv;
267 
268 	/* Perform some operations that aren't actually commands */
269 	comparam = *j->comparam;
270 	down = j->flags & (JF_STOP | JF_FAILED);
271 	switch (comparam) {
272 	case IP_STOP_TIMEOUT:
273 		return term_procs(j);
274 
275 	case IP__OP:
276 		if (down) {
277 			if (jail_remove(j->jid) < 0 && errno == EPERM) {
278 				jail_warnx(j, "jail_remove: %s",
279 					   strerror(errno));
280 				return -1;
281 			}
282 			if (verbose > 0 || (verbose == 0 && (j->flags & JF_STOP
283 			    ? note_remove : j->name != NULL)))
284 			    jail_note(j, "removed\n");
285 			j->jid = -1;
286 			if (j->flags & JF_STOP)
287 				dep_done(j, DF_LIGHT);
288 			else
289 				j->flags &= ~JF_PERSIST;
290 		} else {
291 			if (create_jail(j) < 0)
292 				return -1;
293 			if (iflag)
294 				printf("%d\n", j->jid);
295 			if (verbose >= 0 && (j->name || verbose > 0))
296 				jail_note(j, "created\n");
297 			dep_done(j, DF_LIGHT);
298 		}
299 		return 0;
300 
301 	default: ;
302 	}
303 	/*
304 	 * Collect exec arguments.  Internal commands for network and
305 	 * mounting build their own argument lists.
306 	 */
307 	comstring = j->comstring;
308 	bg = 0;
309 	switch (comparam) {
310 #ifdef INET
311 	case IP__IP4_IFADDR:
312 		argv = alloca(8 * sizeof(char *));
313 		*(const char **)&argv[0] = _PATH_IFCONFIG;
314 		if ((cs = strchr(comstring->s, '|'))) {
315 			argv[1] = alloca(cs - comstring->s + 1);
316 			strlcpy(argv[1], comstring->s, cs - comstring->s + 1);
317 			addr = cs + 1;
318 		} else {
319 			*(const char **)&argv[1] =
320 			    string_param(j->intparams[IP_INTERFACE]);
321 			addr = comstring->s;
322 		}
323 		*(const char **)&argv[2] = "inet";
324 		if (!(cs = strchr(addr, '/'))) {
325 			argv[3] = addr;
326 			*(const char **)&argv[4] = "netmask";
327 			*(const char **)&argv[5] = "255.255.255.255";
328 			argc = 6;
329 		} else if (strchr(cs + 1, '.')) {
330 			argv[3] = alloca(cs - addr + 1);
331 			strlcpy(argv[3], addr, cs - addr + 1);
332 			*(const char **)&argv[4] = "netmask";
333 			*(const char **)&argv[5] = cs + 1;
334 			argc = 6;
335 		} else {
336 			argv[3] = addr;
337 			argc = 4;
338 		}
339 		*(const char **)&argv[argc] = down ? "-alias" : "alias";
340 		argv[argc + 1] = NULL;
341 		break;
342 #endif
343 
344 #ifdef INET6
345 	case IP__IP6_IFADDR:
346 		argv = alloca(8 * sizeof(char *));
347 		*(const char **)&argv[0] = _PATH_IFCONFIG;
348 		if ((cs = strchr(comstring->s, '|'))) {
349 			argv[1] = alloca(cs - comstring->s + 1);
350 			strlcpy(argv[1], comstring->s, cs - comstring->s + 1);
351 			addr = cs + 1;
352 		} else {
353 			*(const char **)&argv[1] =
354 			    string_param(j->intparams[IP_INTERFACE]);
355 			addr = comstring->s;
356 		}
357 		*(const char **)&argv[2] = "inet6";
358 		argv[3] = addr;
359 		if (!(cs = strchr(addr, '/'))) {
360 			*(const char **)&argv[4] = "prefixlen";
361 			*(const char **)&argv[5] = "128";
362 			argc = 6;
363 		} else
364 			argc = 4;
365 		*(const char **)&argv[argc] = down ? "-alias" : "alias";
366 		argv[argc + 1] = NULL;
367 		break;
368 #endif
369 
370 	case IP_VNET_INTERFACE:
371 		argv = alloca(5 * sizeof(char *));
372 		*(const char **)&argv[0] = _PATH_IFCONFIG;
373 		argv[1] = comstring->s;
374 		*(const char **)&argv[2] = down ? "-vnet" : "vnet";
375 		jidstr = string_param(j->intparams[KP_JID]);
376 		*(const char **)&argv[3] =
377 			jidstr ? jidstr : string_param(j->intparams[KP_NAME]);
378 		argv[4] = NULL;
379 		break;
380 
381 	case IP_MOUNT:
382 	case IP__MOUNT_FROM_FSTAB:
383 		argv = alloca(8 * sizeof(char *));
384 		comcs = alloca(comstring->len + 1);
385 		strcpy(comcs, comstring->s);
386 		argc = 0;
387 		for (cs = strtok(comcs, " \t\f\v\r\n"); cs && argc < 4;
388 		     cs = strtok(NULL, " \t\f\v\r\n"))
389 			argv[argc++] = cs;
390 		if (argc == 0)
391 			return 0;
392 		if (argc < 3) {
393 			jail_warnx(j, "%s: %s: missing information",
394 			    j->intparams[comparam]->name, comstring->s);
395 			return -1;
396 		}
397 		if (check_path(j, j->intparams[comparam]->name, argv[1], 0,
398 		    down ? argv[2] : NULL) < 0)
399 			return -1;
400 		if (down) {
401 			argv[4] = NULL;
402 			argv[3] = argv[1];
403 			*(const char **)&argv[0] = "/sbin/umount";
404 		} else {
405 			if (argc == 4) {
406 				argv[7] = NULL;
407 				argv[6] = argv[1];
408 				argv[5] = argv[0];
409 				argv[4] = argv[3];
410 				*(const char **)&argv[3] = "-o";
411 			} else {
412 				argv[5] = NULL;
413 				argv[4] = argv[1];
414 				argv[3] = argv[0];
415 			}
416 			*(const char **)&argv[0] = _PATH_MOUNT;
417 		}
418 		*(const char **)&argv[1] = "-t";
419 		break;
420 
421 	case IP_MOUNT_DEVFS:
422 		argv = alloca(7 * sizeof(char *));
423 		path = string_param(j->intparams[KP_PATH]);
424 		if (path == NULL) {
425 			jail_warnx(j, "mount.devfs: no path");
426 			return -1;
427 		}
428 		devpath = alloca(strlen(path) + 5);
429 		sprintf(devpath, "%s/dev", path);
430 		if (check_path(j, "mount.devfs", devpath, 0,
431 		    down ? "devfs" : NULL) < 0)
432 			return -1;
433 		if (down) {
434 			*(const char **)&argv[0] = "/sbin/umount";
435 			argv[1] = devpath;
436 			argv[2] = NULL;
437 		} else {
438 			*(const char **)&argv[0] = _PATH_MOUNT;
439 			*(const char **)&argv[1] = "-t";
440 			*(const char **)&argv[2] = "devfs";
441 			ruleset = string_param(j->intparams[KP_DEVFS_RULESET]);
442 			if (!ruleset)
443 			    ruleset = "4";	/* devfsrules_jail */
444 			argv[3] = alloca(11 + strlen(ruleset));
445 			sprintf(argv[3], "-oruleset=%s", ruleset);
446 			*(const char **)&argv[4] = ".";
447 			argv[5] = devpath;
448 			argv[6] = NULL;
449 		}
450 		break;
451 
452 	case IP_COMMAND:
453 		if (j->name != NULL)
454 			goto default_command;
455 		argc = 0;
456 		TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
457 			argc++;
458 		argv = alloca((argc + 1) * sizeof(char *));
459 		argc = 0;
460 		TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
461 			argv[argc++] = s->s;
462 		argv[argc] = NULL;
463 		j->comstring = &dummystring;
464 		break;
465 
466 	default:
467 	default_command:
468 		if ((cs = strpbrk(comstring->s, "!\"$&'()*;<>?[\\]`{|}~")) &&
469 		    !(cs[0] == '&' && cs[1] == '\0')) {
470 			argv = alloca(4 * sizeof(char *));
471 			*(const char **)&argv[0] = _PATH_BSHELL;
472 			*(const char **)&argv[1] = "-c";
473 			argv[2] = comstring->s;
474 			argv[3] = NULL;
475 		} else {
476 			if (cs) {
477 				*cs = 0;
478 				bg = 1;
479 			}
480 			comcs = alloca(comstring->len + 1);
481 			strcpy(comcs, comstring->s);
482 			argc = 0;
483 			for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
484 			     cs = strtok(NULL, " \t\f\v\r\n"))
485 				argc++;
486 			argv = alloca((argc + 1) * sizeof(char *));
487 			strcpy(comcs, comstring->s);
488 			argc = 0;
489 			for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
490 			     cs = strtok(NULL, " \t\f\v\r\n"))
491 				argv[argc++] = cs;
492 			argv[argc] = NULL;
493 		}
494 	}
495 	if (argv[0] == NULL)
496 		return 0;
497 
498 	if (int_param(j->intparams[IP_EXEC_TIMEOUT], &timeout) &&
499 	    timeout != 0) {
500 		clock_gettime(CLOCK_REALTIME, &j->timeout);
501 		j->timeout.tv_sec += timeout;
502 	} else
503 		j->timeout.tv_sec = 0;
504 
505 	injail = comparam == IP_EXEC_START || comparam == IP_COMMAND ||
506 	    comparam == IP_EXEC_STOP;
507 	clean = bool_param(j->intparams[IP_EXEC_CLEAN]);
508 	username = string_param(j->intparams[injail
509 	    ? IP_EXEC_JAIL_USER : IP_EXEC_SYSTEM_USER]);
510 	sjuser = bool_param(j->intparams[IP_EXEC_SYSTEM_JAIL_USER]);
511 
512 	consfd = 0;
513 	if (injail &&
514 	    (conslog = string_param(j->intparams[IP_EXEC_CONSOLELOG]))) {
515 		if (check_path(j, "exec.consolelog", conslog, 1, NULL) < 0)
516 			return -1;
517 		consfd =
518 		    open(conslog, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE);
519 		if (consfd < 0) {
520 			jail_warnx(j, "open %s: %s", conslog, strerror(errno));
521 			return -1;
522 		}
523 	}
524 
525 	comlen = 0;
526 	for (i = 0; argv[i]; i++)
527 		comlen += strlen(argv[i]) + 1;
528 	j->comline = cs = emalloc(comlen);
529 	for (i = 0; argv[i]; i++) {
530 		strcpy(cs, argv[i]);
531 		if (argv[i + 1]) {
532 			cs += strlen(argv[i]) + 1;
533 			cs[-1] = ' ';
534 		}
535 	}
536 	if (verbose > 0)
537 		jail_note(j, "run command%s%s%s: %s\n",
538 		    injail ? " in jail" : "", username ? " as " : "",
539 		    username ? username : "", j->comline);
540 
541 	pid = fork();
542 	if (pid < 0)
543 		err(1, "fork");
544 	if (pid > 0) {
545 		if (bg) {
546 			free(j->comline);
547 			j->comline = NULL;
548 			return 0;
549 		} else {
550 			paralimit--;
551 			add_proc(j, pid);
552 			return 1;
553 		}
554 	}
555 	if (bg)
556 		setsid();
557 
558 	/* Set up the environment and run the command */
559 	pwd = NULL;
560 	lcap = NULL;
561 	if ((clean || username) && injail && sjuser &&
562 	    get_user_info(j, username, &pwd, &lcap) < 0)
563 		exit(1);
564 	if (injail) {
565 		/* jail_attach won't chdir along with its chroot. */
566 		path = string_param(j->intparams[KP_PATH]);
567 		if (path && chdir(path) < 0) {
568 			jail_warnx(j, "chdir %s: %s", path, strerror(errno));
569 			exit(1);
570 		}
571 		if (int_param(j->intparams[IP_EXEC_FIB], &fib) &&
572 		    setfib(fib) < 0) {
573 			jail_warnx(j, "setfib: %s", strerror(errno));
574 			exit(1);
575 		}
576 		if (jail_attach(j->jid) < 0) {
577 			jail_warnx(j, "jail_attach: %s", strerror(errno));
578 			exit(1);
579 		}
580 	}
581 	if (clean || username) {
582 		if (!(injail && sjuser) &&
583 		    get_user_info(j, username, &pwd, &lcap) < 0)
584 			exit(1);
585 		if (clean) {
586 			term = getenv("TERM");
587 			environ = &cleanenv;
588 			setenv("PATH", "/bin:/usr/bin", 0);
589 			if (term != NULL)
590 				setenv("TERM", term, 1);
591 		}
592 		if (setusercontext(lcap, pwd, pwd->pw_uid, username
593 		    ? LOGIN_SETALL & ~LOGIN_SETGROUP & ~LOGIN_SETLOGIN
594 		    : LOGIN_SETPATH | LOGIN_SETENV) < 0) {
595 			jail_warnx(j, "setusercontext %s: %s", pwd->pw_name,
596 			    strerror(errno));
597 			exit(1);
598 		}
599 		login_close(lcap);
600 		setenv("USER", pwd->pw_name, 1);
601 		setenv("HOME", pwd->pw_dir, 1);
602 		setenv("SHELL",
603 		    *pwd->pw_shell ? pwd->pw_shell : _PATH_BSHELL, 1);
604 		if (clean && chdir(pwd->pw_dir) < 0) {
605 			jail_warnx(j, "chdir %s: %s",
606 			    pwd->pw_dir, strerror(errno));
607 			exit(1);
608 		}
609 		endpwent();
610 	}
611 
612 	if (consfd != 0 && (dup2(consfd, 1) < 0 || dup2(consfd, 2) < 0)) {
613 		jail_warnx(j, "exec.consolelog: %s", strerror(errno));
614 		exit(1);
615 	}
616 	closefrom(3);
617 	execvp(argv[0], argv);
618 	jail_warnx(j, "exec %s: %s", argv[0], strerror(errno));
619 	exit(1);
620 }
621 
622 /*
623  * Add a process to the hash, tied to a jail.
624  */
625 static void
626 add_proc(struct cfjail *j, pid_t pid)
627 {
628 	struct kevent ke;
629 	struct cfjail *tj;
630 	struct phash *ph;
631 
632 	if (!kq && (kq = kqueue()) < 0)
633 		err(1, "kqueue");
634 	EV_SET(&ke, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
635 	if (kevent(kq, &ke, 1, NULL, 0, NULL) < 0)
636 		err(1, "kevent");
637 	ph = emalloc(sizeof(struct phash));
638 	ph->j = j;
639 	ph->pid = pid;
640 	LIST_INSERT_HEAD(&phash[pid % PHASH_SIZE], ph, le);
641 	j->nprocs++;
642 	j->flags |= JF_SLEEPQ;
643 	if (j->timeout.tv_sec == 0)
644 		requeue(j, &sleeping);
645 	else {
646 		/* File the jail in the sleep queue acording to its timeout. */
647 		TAILQ_REMOVE(j->queue, j, tq);
648 		TAILQ_FOREACH(tj, &sleeping, tq) {
649 			if (!tj->timeout.tv_sec ||
650 			    j->timeout.tv_sec < tj->timeout.tv_sec ||
651 			    (j->timeout.tv_sec == tj->timeout.tv_sec &&
652 			    j->timeout.tv_nsec <= tj->timeout.tv_nsec)) {
653 				TAILQ_INSERT_BEFORE(tj, j, tq);
654 				break;
655 			}
656 		}
657 		if (tj == NULL)
658 			TAILQ_INSERT_TAIL(&sleeping, j, tq);
659 		j->queue = &sleeping;
660 	}
661 }
662 
663 /*
664  * Remove any processes from the hash that correspond to a jail.
665  */
666 static void
667 clear_procs(struct cfjail *j)
668 {
669 	struct kevent ke;
670 	struct phash *ph, *tph;
671 	int i;
672 
673 	j->nprocs = 0;
674 	for (i = 0; i < PHASH_SIZE; i++)
675 		LIST_FOREACH_SAFE(ph, &phash[i], le, tph)
676 			if (ph->j == j) {
677 				EV_SET(&ke, ph->pid, EVFILT_PROC, EV_DELETE,
678 				    NOTE_EXIT, 0, NULL);
679 				(void)kevent(kq, &ke, 1, NULL, 0, NULL);
680 				LIST_REMOVE(ph, le);
681 				free(ph);
682 			}
683 }
684 
685 /*
686  * Find the jail that corresponds to an exited process.
687  */
688 static struct cfjail *
689 find_proc(pid_t pid)
690 {
691 	struct cfjail *j;
692 	struct phash *ph;
693 
694 	LIST_FOREACH(ph, &phash[pid % PHASH_SIZE], le)
695 		if (ph->pid == pid) {
696 			j = ph->j;
697 			LIST_REMOVE(ph, le);
698 			free(ph);
699 			return --j->nprocs ? NULL : j;
700 		}
701 	return NULL;
702 }
703 
704 /*
705  * Send SIGTERM to all processes in a jail and wait for them to die.
706  */
707 static int
708 term_procs(struct cfjail *j)
709 {
710 	struct kinfo_proc *ki;
711 	int i, noted, pcnt, timeout;
712 
713 	static kvm_t *kd;
714 
715 	if (!int_param(j->intparams[IP_STOP_TIMEOUT], &timeout))
716 		timeout = DEFAULT_STOP_TIMEOUT;
717 	else if (timeout == 0)
718 		return 0;
719 
720 	if (kd == NULL) {
721 		kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
722 		if (kd == NULL)
723 			return 0;
724 	}
725 
726 	ki = kvm_getprocs(kd, KERN_PROC_PROC, 0, &pcnt);
727 	if (ki == NULL)
728 		return 0;
729 	noted = 0;
730 	for (i = 0; i < pcnt; i++)
731 		if (ki[i].ki_jid == j->jid &&
732 		    kill(ki[i].ki_pid, SIGTERM) == 0) {
733 			add_proc(j, ki[i].ki_pid);
734 			if (verbose > 0) {
735 				if (!noted) {
736 					noted = 1;
737 					jail_note(j, "sent SIGTERM to:");
738 				}
739 				printf(" %d", ki[i].ki_pid);
740 			}
741 		}
742 	if (noted)
743 		printf("\n");
744 	if (j->nprocs > 0) {
745 		clock_gettime(CLOCK_REALTIME, &j->timeout);
746 		j->timeout.tv_sec += timeout;
747 		return 1;
748 	}
749 	return 0;
750 }
751 
752 /*
753  * Look up a user in the passwd and login.conf files.
754  */
755 static int
756 get_user_info(struct cfjail *j, const char *username,
757     const struct passwd **pwdp, login_cap_t **lcapp)
758 {
759 	const struct passwd *pwd;
760 
761 	*pwdp = pwd = username ? getpwnam(username) : getpwuid(getuid());
762 	if (pwd == NULL) {
763 		if (errno)
764 			jail_warnx(j, "getpwnam%s%s: %s", username ? " " : "",
765 			    username ? username : "", strerror(errno));
766 		else if (username)
767 			jail_warnx(j, "%s: no such user", username);
768 		else
769 			jail_warnx(j, "unknown uid %d", getuid());
770 		return -1;
771 	}
772 	*lcapp = login_getpwclass(pwd);
773 	if (*lcapp == NULL) {
774 		jail_warnx(j, "getpwclass %s: %s", pwd->pw_name,
775 		    strerror(errno));
776 		return -1;
777 	}
778 	/* Set the groups while the group file is still available */
779 	if (initgroups(pwd->pw_name, pwd->pw_gid) < 0) {
780 		jail_warnx(j, "initgroups %s: %s", pwd->pw_name,
781 		    strerror(errno));
782 		return -1;
783 	}
784 	return 0;
785 }
786 
787 /*
788  * Make sure a mount or consolelog path is a valid absolute pathname
789  * with no symlinks.
790  */
791 static int
792 check_path(struct cfjail *j, const char *pname, const char *path, int isfile,
793     const char *umount_type)
794 {
795 	struct stat st, mpst;
796 	struct statfs stfs;
797 	char *tpath, *p;
798 	const char *jailpath;
799 	size_t jplen;
800 
801 	if (path[0] != '/') {
802 		jail_warnx(j, "%s: %s: not an absolute pathname",
803 		    pname, path);
804 		return -1;
805 	}
806 	/*
807 	 * Only check for symlinks in components below the jail's path,
808 	 * since that's where the security risk lies.
809 	 */
810 	jailpath = string_param(j->intparams[KP_PATH]);
811 	if (jailpath == NULL)
812 		jailpath = "";
813 	jplen = strlen(jailpath);
814 	if (!strncmp(path, jailpath, jplen) && path[jplen] == '/') {
815 		tpath = alloca(strlen(path) + 1);
816 		strcpy(tpath, path);
817 		for (p = tpath + jplen; p != NULL; ) {
818 			p = strchr(p + 1, '/');
819 			if (p)
820 				*p = '\0';
821 			if (lstat(tpath, &st) < 0) {
822 				if (errno == ENOENT && isfile && !p)
823 					break;
824 				jail_warnx(j, "%s: %s: %s", pname, tpath,
825 				    strerror(errno));
826 				return -1;
827 			}
828 			if (S_ISLNK(st.st_mode)) {
829 				jail_warnx(j, "%s: %s is a symbolic link",
830 				    pname, tpath);
831 				return -1;
832 			}
833 			if (p)
834 				*p = '/';
835 		}
836 	}
837 	if (umount_type != NULL) {
838 		if (stat(path, &st) < 0 || statfs(path, &stfs) < 0) {
839 			jail_warnx(j, "%s: %s: %s", pname, path,
840 			    strerror(errno));
841 			return -1;
842 		}
843 		if (stat(stfs.f_mntonname, &mpst) < 0) {
844 			jail_warnx(j, "%s: %s: %s", pname, stfs.f_mntonname,
845 			    strerror(errno));
846 			return -1;
847 		}
848 		if (st.st_ino != mpst.st_ino) {
849 			jail_warnx(j, "%s: %s: not a mount point",
850 			    pname, path);
851 			return -1;
852 		}
853 		if (strcmp(stfs.f_fstypename, umount_type)) {
854 			jail_warnx(j, "%s: %s: not a %s mount",
855 			    pname, path, umount_type);
856 			return -1;
857 		}
858 	}
859 	return 0;
860 }
861