xref: /freebsd/usr.sbin/jail/command.c (revision 445ed7b40948c160f2f7d363d2d0ae1ffac4aabd)
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 int 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, stopping;
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 	stopping = (j->flags & JF_STOP) != 0;
99 	comparam = *j->comparam;
100 	for (;;) {
101 		if (j->comstring == NULL) {
102 			j->comparam += create_failed ? -1 : 1;
103 			switch ((comparam = *j->comparam)) {
104 			case IP__NULL:
105 				return 0;
106 			case IP_MOUNT_DEVFS:
107 				if (!bool_param(j->intparams[IP_MOUNT_DEVFS]))
108 					continue;
109 				j->comstring = &dummystring;
110 				break;
111 			case IP_MOUNT_FDESCFS:
112 				if (!bool_param(j->intparams[IP_MOUNT_FDESCFS]))
113 					continue;
114 				j->comstring = &dummystring;
115 			case IP__OP:
116 			case IP_STOP_TIMEOUT:
117 				j->comstring = &dummystring;
118 				break;
119 			default:
120 				if (j->intparams[comparam] == NULL)
121 					continue;
122 				j->comstring = create_failed || (stopping &&
123 				    (j->intparams[comparam]->flags & PF_REV))
124 				    ? TAILQ_LAST(&j->intparams[comparam]->val,
125 					cfstrings)
126 				    : TAILQ_FIRST(&j->intparams[comparam]->val);
127 			}
128 		} else {
129 			j->comstring = j->comstring == &dummystring ? NULL :
130 			    create_failed || (stopping &&
131 			    (j->intparams[comparam]->flags & PF_REV))
132 			    ? TAILQ_PREV(j->comstring, cfstrings, tq)
133 			    : TAILQ_NEXT(j->comstring, tq);
134 		}
135 		if (j->comstring == NULL || j->comstring->len == 0 ||
136 		    (create_failed && (comparam == IP_EXEC_PRESTART ||
137 		    comparam == IP_EXEC_START || comparam == IP_COMMAND ||
138 		    comparam == IP_EXEC_POSTSTART)))
139 			continue;
140 		switch (run_command(j)) {
141 		case -1:
142 			failed(j);
143 			/* FALLTHROUGH */
144 		case 1:
145 			return 1;
146 		}
147 	}
148 }
149 
150 /*
151  * Check command exit status
152  */
153 int
154 finish_command(struct cfjail *j)
155 {
156 	int error;
157 
158 	if (!(j->flags & JF_SLEEPQ))
159 		return 0;
160 	j->flags &= ~JF_SLEEPQ;
161 	if (*j->comparam == IP_STOP_TIMEOUT)
162 	{
163 		j->flags &= ~JF_TIMEOUT;
164 		j->pstatus = 0;
165 		return 0;
166 	}
167 	paralimit++;
168 	if (!TAILQ_EMPTY(&runnable))
169 		requeue(TAILQ_FIRST(&runnable), &ready);
170 	error = 0;
171 	if (j->flags & JF_TIMEOUT) {
172 		j->flags &= ~JF_TIMEOUT;
173 		if (*j->comparam != IP_STOP_TIMEOUT) {
174 			jail_warnx(j, "%s: timed out", j->comline);
175 			failed(j);
176 			error = -1;
177 		} else if (verbose > 0)
178 			jail_note(j, "timed out\n");
179 	} else if (j->pstatus != 0) {
180 		if (WIFSIGNALED(j->pstatus))
181 			jail_warnx(j, "%s: exited on signal %d",
182 			    j->comline, WTERMSIG(j->pstatus));
183 		else
184 			jail_warnx(j, "%s: failed", j->comline);
185 		j->pstatus = 0;
186 		failed(j);
187 		error = -1;
188 	}
189 	free(j->comline);
190 	j->comline = NULL;
191 	return error;
192 }
193 
194 /*
195  * Check for finished processes or timeouts.
196  */
197 struct cfjail *
198 next_proc(int nonblock)
199 {
200 	struct kevent ke;
201 	struct timespec ts;
202 	struct timespec *tsp;
203 	struct cfjail *j;
204 
205 	if (!TAILQ_EMPTY(&sleeping)) {
206 	again:
207 		tsp = NULL;
208 		if ((j = TAILQ_FIRST(&sleeping)) && j->timeout.tv_sec) {
209 			clock_gettime(CLOCK_REALTIME, &ts);
210 			ts.tv_sec = j->timeout.tv_sec - ts.tv_sec;
211 			ts.tv_nsec = j->timeout.tv_nsec - ts.tv_nsec;
212 			if (ts.tv_nsec < 0) {
213 				ts.tv_sec--;
214 				ts.tv_nsec += 1000000000;
215 			}
216 			if (ts.tv_sec < 0 ||
217 			    (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
218 				j->flags |= JF_TIMEOUT;
219 				clear_procs(j);
220 				return j;
221 			}
222 			tsp = &ts;
223 		}
224 		if (nonblock) {
225 			ts.tv_sec = 0;
226 			ts.tv_nsec = 0;
227 			tsp = &ts;
228 		}
229 		switch (kevent(kq, NULL, 0, &ke, 1, tsp)) {
230 		case -1:
231 			if (errno != EINTR)
232 				err(1, "kevent");
233 			goto again;
234 		case 0:
235 			if (!nonblock) {
236 				j = TAILQ_FIRST(&sleeping);
237 				j->flags |= JF_TIMEOUT;
238 				clear_procs(j);
239 				return j;
240 			}
241 			break;
242 		case 1:
243 			(void)waitpid(ke.ident, NULL, WNOHANG);
244 			if ((j = find_proc(ke.ident))) {
245 				j->pstatus = ke.data;
246 				return j;
247 			}
248 			goto again;
249 		}
250 	}
251 	return NULL;
252 }
253 
254 /*
255  * Run a single command for a jail, possible inside the jail.
256  */
257 static int
258 run_command(struct cfjail *j)
259 {
260 	const struct passwd *pwd;
261 	const struct cfstring *comstring, *s;
262 	login_cap_t *lcap;
263 	const char **argv;
264 	char *acs, *cs, *comcs, *devpath;
265 	const char *jidstr, *conslog, *path, *ruleset, *term, *username;
266 	enum intparam comparam;
267 	size_t comlen;
268 	pid_t pid;
269 	int argc, bg, clean, consfd, down, fib, i, injail, sjuser, timeout;
270 #if defined(INET) || defined(INET6)
271 	char *addr, *extrap, *p, *val;
272 #endif
273 
274 	static char *cleanenv;
275 
276 	/* Perform some operations that aren't actually commands */
277 	comparam = *j->comparam;
278 	down = j->flags & (JF_STOP | JF_FAILED);
279 	switch (comparam) {
280 	case IP_STOP_TIMEOUT:
281 		return term_procs(j);
282 
283 	case IP__OP:
284 		if (down) {
285 			if (jail_remove(j->jid) < 0 && errno == EPERM) {
286 				jail_warnx(j, "jail_remove: %s",
287 					   strerror(errno));
288 				return -1;
289 			}
290 			if (verbose > 0 || (verbose == 0 && (j->flags & JF_STOP
291 			    ? note_remove : j->name != NULL)))
292 			    jail_note(j, "removed\n");
293 			j->jid = -1;
294 			if (j->flags & JF_STOP)
295 				dep_done(j, DF_LIGHT);
296 			else
297 				j->flags &= ~JF_PERSIST;
298 		} else {
299 			if (create_jail(j) < 0)
300 				return -1;
301 			if (iflag)
302 				printf("%d\n", j->jid);
303 			if (verbose >= 0 && (j->name || verbose > 0))
304 				jail_note(j, "created\n");
305 			dep_done(j, DF_LIGHT);
306 		}
307 		return 0;
308 
309 	default: ;
310 	}
311 	/*
312 	 * Collect exec arguments.  Internal commands for network and
313 	 * mounting build their own argument lists.
314 	 */
315 	comstring = j->comstring;
316 	bg = 0;
317 	switch (comparam) {
318 #ifdef INET
319 	case IP__IP4_IFADDR:
320 		argc = 0;
321 		val = alloca(strlen(comstring->s) + 1);
322 		strcpy(val, comstring->s);
323 		cs = val;
324 		extrap = NULL;
325 		while ((p = strchr(cs, ' ')) != NULL && strlen(p) > 1) {
326 			if (extrap == NULL) {
327 				*p = '\0';
328 				extrap = p + 1;
329 			}
330 			cs = p + 1;
331 			argc++;
332 		}
333 
334 		argv = alloca((8 + argc) * sizeof(char *));
335 		argv[0] = _PATH_IFCONFIG;
336 		if ((cs = strchr(val, '|'))) {
337 			argv[1] = acs = alloca(cs - val + 1);
338 			strlcpy(acs, val, cs - val + 1);
339 			addr = cs + 1;
340 		} else {
341 			argv[1] = string_param(j->intparams[IP_INTERFACE]);
342 			addr = val;
343 		}
344 		argv[2] = "inet";
345 		if (!(cs = strchr(addr, '/'))) {
346 			argv[3] = addr;
347 			argv[4] = "netmask";
348 			argv[5] = "255.255.255.255";
349 			argc = 6;
350 		} else if (strchr(cs + 1, '.')) {
351 			argv[3] = acs = alloca(cs - addr + 1);
352 			strlcpy(acs, addr, cs - addr + 1);
353 			argv[4] = "netmask";
354 			argv[5] = cs + 1;
355 			argc = 6;
356 		} else {
357 			argv[3] = addr;
358 			argc = 4;
359 		}
360 
361 		if (!down) {
362 			for (cs = strtok(extrap, " "); cs;
363 			     cs = strtok(NULL, " ")) {
364 				size_t len = strlen(cs) + 1;
365 				argv[argc++] = acs = alloca(len);
366 				strlcpy(acs, cs, len);
367 			}
368 		}
369 
370 		argv[argc] = down ? "-alias" : "alias";
371 		argv[argc + 1] = NULL;
372 		break;
373 #endif
374 
375 #ifdef INET6
376 	case IP__IP6_IFADDR:
377 		argc = 0;
378 		val = alloca(strlen(comstring->s) + 1);
379 		strcpy(val, comstring->s);
380 		cs = val;
381 		extrap = NULL;
382 		while ((p = strchr(cs, ' ')) != NULL && strlen(p) > 1) {
383 			if (extrap == NULL) {
384 				*p = '\0';
385 				extrap = p + 1;
386 			}
387 			cs = p + 1;
388 			argc++;
389 		}
390 
391 		argv = alloca((8 + argc) * sizeof(char *));
392 		argv[0] = _PATH_IFCONFIG;
393 		if ((cs = strchr(val, '|'))) {
394 			argv[1] = acs = alloca(cs - val + 1);
395 			strlcpy(acs, val, cs - val + 1);
396 			addr = cs + 1;
397 		} else {
398 			argv[1] = string_param(j->intparams[IP_INTERFACE]);
399 			addr = val;
400 		}
401 		argv[2] = "inet6";
402 		argv[3] = addr;
403 		if (!(cs = strchr(addr, '/'))) {
404 			argv[4] = "prefixlen";
405 			argv[5] = "128";
406 			argc = 6;
407 		} else
408 			argc = 4;
409 
410 		if (!down) {
411 			for (cs = strtok(extrap, " "); cs;
412 			     cs = strtok(NULL, " ")) {
413 				size_t len = strlen(cs) + 1;
414 				argv[argc++] = acs = alloca(len);
415 				strlcpy(acs, cs, len);
416 			}
417 		}
418 
419 		argv[argc] = down ? "-alias" : "alias";
420 		argv[argc + 1] = NULL;
421 		break;
422 #endif
423 
424 	case IP_VNET_INTERFACE:
425 		argv = alloca(5 * sizeof(char *));
426 		argv[0] = _PATH_IFCONFIG;
427 		argv[1] = comstring->s;
428 		argv[2] = down ? "-vnet" : "vnet";
429 		jidstr = string_param(j->intparams[KP_JID]);
430 		argv[3] = jidstr ? jidstr : string_param(j->intparams[KP_NAME]);
431 		argv[4] = NULL;
432 		break;
433 
434 	case IP_MOUNT:
435 	case IP__MOUNT_FROM_FSTAB:
436 		argv = alloca(8 * sizeof(char *));
437 		comcs = alloca(comstring->len + 1);
438 		strcpy(comcs, comstring->s);
439 		argc = 0;
440 		for (cs = strtok(comcs, " \t\f\v\r\n"); cs && argc < 4;
441 		     cs = strtok(NULL, " \t\f\v\r\n"))
442 			argv[argc++] = cs;
443 		if (argc == 0)
444 			return 0;
445 		if (argc < 3) {
446 			jail_warnx(j, "%s: %s: missing information",
447 			    j->intparams[comparam]->name, comstring->s);
448 			return -1;
449 		}
450 		if (check_path(j, j->intparams[comparam]->name, argv[1], 0,
451 		    down ? argv[2] : NULL) < 0)
452 			return -1;
453 		if (down) {
454 			argv[4] = NULL;
455 			argv[3] = argv[1];
456 			argv[0] = "/sbin/umount";
457 		} else {
458 			if (argc == 4) {
459 				argv[7] = NULL;
460 				argv[6] = argv[1];
461 				argv[5] = argv[0];
462 				argv[4] = argv[3];
463 				argv[3] = "-o";
464 			} else {
465 				argv[5] = NULL;
466 				argv[4] = argv[1];
467 				argv[3] = argv[0];
468 			}
469 			argv[0] = _PATH_MOUNT;
470 		}
471 		argv[1] = "-t";
472 		break;
473 
474 	case IP_MOUNT_DEVFS:
475 		argv = alloca(7 * sizeof(char *));
476 		path = string_param(j->intparams[KP_PATH]);
477 		if (path == NULL) {
478 			jail_warnx(j, "mount.devfs: no path");
479 			return -1;
480 		}
481 		devpath = alloca(strlen(path) + 5);
482 		sprintf(devpath, "%s/dev", path);
483 		if (check_path(j, "mount.devfs", devpath, 0,
484 		    down ? "devfs" : NULL) < 0)
485 			return -1;
486 		if (down) {
487 			argv[0] = "/sbin/umount";
488 			argv[1] = devpath;
489 			argv[2] = NULL;
490 		} else {
491 			argv[0] = _PATH_MOUNT;
492 			argv[1] = "-t";
493 			argv[2] = "devfs";
494 			ruleset = string_param(j->intparams[KP_DEVFS_RULESET]);
495 			if (!ruleset)
496 			    ruleset = "4";	/* devfsrules_jail */
497 			argv[3] = acs = alloca(11 + strlen(ruleset));
498 			sprintf(acs, "-oruleset=%s", ruleset);
499 			argv[4] = ".";
500 			argv[5] = devpath;
501 			argv[6] = NULL;
502 		}
503 		break;
504 
505 	case IP_MOUNT_FDESCFS:
506 		argv = alloca(7 * sizeof(char *));
507 		path = string_param(j->intparams[KP_PATH]);
508 		if (path == NULL) {
509 			jail_warnx(j, "mount.fdescfs: no path");
510 			return -1;
511 		}
512 		devpath = alloca(strlen(path) + 8);
513 		sprintf(devpath, "%s/dev/fd", path);
514 		if (check_path(j, "mount.fdescfs", devpath, 0,
515 		    down ? "fdescfs" : NULL) < 0)
516 			return -1;
517 		if (down) {
518 			argv[0] = "/sbin/umount";
519 			argv[1] = devpath;
520 			argv[2] = NULL;
521 		} else {
522 			argv[0] = _PATH_MOUNT;
523 			argv[1] = "-t";
524 			argv[2] = "fdescfs";
525 			argv[3] = ".";
526 			argv[4] = devpath;
527 			argv[5] = NULL;
528 		}
529 		break;
530 
531 	case IP_COMMAND:
532 		if (j->name != NULL)
533 			goto default_command;
534 		argc = 0;
535 		TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
536 			argc++;
537 		argv = alloca((argc + 1) * sizeof(char *));
538 		argc = 0;
539 		TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
540 			argv[argc++] = s->s;
541 		argv[argc] = NULL;
542 		j->comstring = &dummystring;
543 		break;
544 
545 	default:
546 	default_command:
547 		if ((cs = strpbrk(comstring->s, "!\"$&'()*;<>?[\\]`{|}~")) &&
548 		    !(cs[0] == '&' && cs[1] == '\0')) {
549 			argv = alloca(4 * sizeof(char *));
550 			argv[0] = _PATH_BSHELL;
551 			argv[1] = "-c";
552 			argv[2] = comstring->s;
553 			argv[3] = NULL;
554 		} else {
555 			if (cs) {
556 				*cs = 0;
557 				bg = 1;
558 			}
559 			comcs = alloca(comstring->len + 1);
560 			strcpy(comcs, comstring->s);
561 			argc = 0;
562 			for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
563 			     cs = strtok(NULL, " \t\f\v\r\n"))
564 				argc++;
565 			argv = alloca((argc + 1) * sizeof(char *));
566 			strcpy(comcs, comstring->s);
567 			argc = 0;
568 			for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
569 			     cs = strtok(NULL, " \t\f\v\r\n"))
570 				argv[argc++] = cs;
571 			argv[argc] = NULL;
572 		}
573 	}
574 	if (argv[0] == NULL)
575 		return 0;
576 
577 	if (int_param(j->intparams[IP_EXEC_TIMEOUT], &timeout) &&
578 	    timeout != 0) {
579 		clock_gettime(CLOCK_REALTIME, &j->timeout);
580 		j->timeout.tv_sec += timeout;
581 	} else
582 		j->timeout.tv_sec = 0;
583 
584 	injail = comparam == IP_EXEC_START || comparam == IP_COMMAND ||
585 	    comparam == IP_EXEC_STOP;
586 	clean = bool_param(j->intparams[IP_EXEC_CLEAN]);
587 	username = string_param(j->intparams[injail
588 	    ? IP_EXEC_JAIL_USER : IP_EXEC_SYSTEM_USER]);
589 	sjuser = bool_param(j->intparams[IP_EXEC_SYSTEM_JAIL_USER]);
590 
591 	consfd = 0;
592 	if (injail &&
593 	    (conslog = string_param(j->intparams[IP_EXEC_CONSOLELOG]))) {
594 		if (check_path(j, "exec.consolelog", conslog, 1, NULL) < 0)
595 			return -1;
596 		consfd =
597 		    open(conslog, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE);
598 		if (consfd < 0) {
599 			jail_warnx(j, "open %s: %s", conslog, strerror(errno));
600 			return -1;
601 		}
602 	}
603 
604 	comlen = 0;
605 	for (i = 0; argv[i]; i++)
606 		comlen += strlen(argv[i]) + 1;
607 	j->comline = cs = emalloc(comlen);
608 	for (i = 0; argv[i]; i++) {
609 		strcpy(cs, argv[i]);
610 		if (argv[i + 1]) {
611 			cs += strlen(argv[i]) + 1;
612 			cs[-1] = ' ';
613 		}
614 	}
615 	if (verbose > 0)
616 		jail_note(j, "run command%s%s%s: %s\n",
617 		    injail ? " in jail" : "", username ? " as " : "",
618 		    username ? username : "", j->comline);
619 
620 	pid = fork();
621 	if (pid < 0)
622 		err(1, "fork");
623 	if (pid > 0) {
624 		if (bg || !add_proc(j, pid)) {
625 			free(j->comline);
626 			j->comline = NULL;
627 			return 0;
628 		} else {
629 			paralimit--;
630 			return 1;
631 		}
632 	}
633 	if (bg)
634 		setsid();
635 
636 	/* Set up the environment and run the command */
637 	pwd = NULL;
638 	lcap = NULL;
639 	if ((clean || username) && injail && sjuser &&
640 	    get_user_info(j, username, &pwd, &lcap) < 0)
641 		exit(1);
642 	if (injail) {
643 		/* jail_attach won't chdir along with its chroot. */
644 		path = string_param(j->intparams[KP_PATH]);
645 		if (path && chdir(path) < 0) {
646 			jail_warnx(j, "chdir %s: %s", path, strerror(errno));
647 			exit(1);
648 		}
649 		if (int_param(j->intparams[IP_EXEC_FIB], &fib) &&
650 		    setfib(fib) < 0) {
651 			jail_warnx(j, "setfib: %s", strerror(errno));
652 			exit(1);
653 		}
654 		if (jail_attach(j->jid) < 0) {
655 			jail_warnx(j, "jail_attach: %s", strerror(errno));
656 			exit(1);
657 		}
658 	}
659 	if (clean || username) {
660 		if (!(injail && sjuser) &&
661 		    get_user_info(j, username, &pwd, &lcap) < 0)
662 			exit(1);
663 		if (clean) {
664 			term = getenv("TERM");
665 			environ = &cleanenv;
666 			setenv("PATH", "/bin:/usr/bin", 0);
667 			if (term != NULL)
668 				setenv("TERM", term, 1);
669 		}
670 		if (setgid(pwd->pw_gid) < 0) {
671 			jail_warnx(j, "setgid %d: %s", pwd->pw_gid,
672 			    strerror(errno));
673 			exit(1);
674 		}
675 		if (setusercontext(lcap, pwd, pwd->pw_uid, username
676 		    ? LOGIN_SETALL & ~LOGIN_SETGROUP & ~LOGIN_SETLOGIN
677 		    : LOGIN_SETPATH | LOGIN_SETENV) < 0) {
678 			jail_warnx(j, "setusercontext %s: %s", pwd->pw_name,
679 			    strerror(errno));
680 			exit(1);
681 		}
682 		login_close(lcap);
683 		setenv("USER", pwd->pw_name, 1);
684 		setenv("HOME", pwd->pw_dir, 1);
685 		setenv("SHELL",
686 		    *pwd->pw_shell ? pwd->pw_shell : _PATH_BSHELL, 1);
687 		if (clean && chdir(pwd->pw_dir) < 0) {
688 			jail_warnx(j, "chdir %s: %s",
689 			    pwd->pw_dir, strerror(errno));
690 			exit(1);
691 		}
692 		endpwent();
693 	}
694 
695 	if (consfd != 0 && (dup2(consfd, 1) < 0 || dup2(consfd, 2) < 0)) {
696 		jail_warnx(j, "exec.consolelog: %s", strerror(errno));
697 		exit(1);
698 	}
699 	closefrom(3);
700 	execvp(argv[0], __DECONST(char *const*, argv));
701 	jail_warnx(j, "exec %s: %s", argv[0], strerror(errno));
702 	exit(1);
703 }
704 
705 /*
706  * Add a process to the hash, tied to a jail.
707  */
708 static int
709 add_proc(struct cfjail *j, pid_t pid)
710 {
711 	struct kevent ke;
712 	struct cfjail *tj;
713 	struct phash *ph;
714 
715 	if (!kq && (kq = kqueue()) < 0)
716 		err(1, "kqueue");
717 	EV_SET(&ke, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
718 	if (kevent(kq, &ke, 1, NULL, 0, NULL) < 0) {
719 		if (errno == ESRCH)
720 			return 0;
721 		err(1, "kevent");
722 	}
723 	ph = emalloc(sizeof(struct phash));
724 	ph->j = j;
725 	ph->pid = pid;
726 	LIST_INSERT_HEAD(&phash[pid % PHASH_SIZE], ph, le);
727 	j->nprocs++;
728 	j->flags |= JF_SLEEPQ;
729 	if (j->timeout.tv_sec == 0)
730 		requeue(j, &sleeping);
731 	else {
732 		/* File the jail in the sleep queue acording to its timeout. */
733 		TAILQ_REMOVE(j->queue, j, tq);
734 		TAILQ_FOREACH(tj, &sleeping, tq) {
735 			if (!tj->timeout.tv_sec ||
736 			    j->timeout.tv_sec < tj->timeout.tv_sec ||
737 			    (j->timeout.tv_sec == tj->timeout.tv_sec &&
738 			    j->timeout.tv_nsec <= tj->timeout.tv_nsec)) {
739 				TAILQ_INSERT_BEFORE(tj, j, tq);
740 				break;
741 			}
742 		}
743 		if (tj == NULL)
744 			TAILQ_INSERT_TAIL(&sleeping, j, tq);
745 		j->queue = &sleeping;
746 	}
747 	return 1;
748 }
749 
750 /*
751  * Remove any processes from the hash that correspond to a jail.
752  */
753 static void
754 clear_procs(struct cfjail *j)
755 {
756 	struct kevent ke;
757 	struct phash *ph, *tph;
758 	int i;
759 
760 	j->nprocs = 0;
761 	for (i = 0; i < PHASH_SIZE; i++)
762 		LIST_FOREACH_SAFE(ph, &phash[i], le, tph)
763 			if (ph->j == j) {
764 				EV_SET(&ke, ph->pid, EVFILT_PROC, EV_DELETE,
765 				    NOTE_EXIT, 0, NULL);
766 				(void)kevent(kq, &ke, 1, NULL, 0, NULL);
767 				LIST_REMOVE(ph, le);
768 				free(ph);
769 			}
770 }
771 
772 /*
773  * Find the jail that corresponds to an exited process.
774  */
775 static struct cfjail *
776 find_proc(pid_t pid)
777 {
778 	struct cfjail *j;
779 	struct phash *ph;
780 
781 	LIST_FOREACH(ph, &phash[pid % PHASH_SIZE], le)
782 		if (ph->pid == pid) {
783 			j = ph->j;
784 			LIST_REMOVE(ph, le);
785 			free(ph);
786 			return --j->nprocs ? NULL : j;
787 		}
788 	return NULL;
789 }
790 
791 /*
792  * Send SIGTERM to all processes in a jail and wait for them to die.
793  */
794 static int
795 term_procs(struct cfjail *j)
796 {
797 	struct kinfo_proc *ki;
798 	int i, noted, pcnt, timeout;
799 
800 	static kvm_t *kd;
801 
802 	if (!int_param(j->intparams[IP_STOP_TIMEOUT], &timeout))
803 		timeout = DEFAULT_STOP_TIMEOUT;
804 	else if (timeout == 0)
805 		return 0;
806 
807 	if (kd == NULL) {
808 		kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
809 		if (kd == NULL)
810 			return 0;
811 	}
812 
813 	ki = kvm_getprocs(kd, KERN_PROC_PROC, 0, &pcnt);
814 	if (ki == NULL)
815 		return 0;
816 	noted = 0;
817 	for (i = 0; i < pcnt; i++)
818 		if (ki[i].ki_jid == j->jid &&
819 		    kill(ki[i].ki_pid, SIGTERM) == 0) {
820 			(void)add_proc(j, ki[i].ki_pid);
821 			if (verbose > 0) {
822 				if (!noted) {
823 					noted = 1;
824 					jail_note(j, "sent SIGTERM to:");
825 				}
826 				printf(" %d", ki[i].ki_pid);
827 			}
828 		}
829 	if (noted)
830 		printf("\n");
831 	if (j->nprocs > 0) {
832 		clock_gettime(CLOCK_REALTIME, &j->timeout);
833 		j->timeout.tv_sec += timeout;
834 		return 1;
835 	}
836 	return 0;
837 }
838 
839 /*
840  * Look up a user in the passwd and login.conf files.
841  */
842 static int
843 get_user_info(struct cfjail *j, const char *username,
844     const struct passwd **pwdp, login_cap_t **lcapp)
845 {
846 	const struct passwd *pwd;
847 
848 	*pwdp = pwd = username ? getpwnam(username) : getpwuid(getuid());
849 	if (pwd == NULL) {
850 		if (errno)
851 			jail_warnx(j, "getpwnam%s%s: %s", username ? " " : "",
852 			    username ? username : "", strerror(errno));
853 		else if (username)
854 			jail_warnx(j, "%s: no such user", username);
855 		else
856 			jail_warnx(j, "unknown uid %d", getuid());
857 		return -1;
858 	}
859 	*lcapp = login_getpwclass(pwd);
860 	if (*lcapp == NULL) {
861 		jail_warnx(j, "getpwclass %s: %s", pwd->pw_name,
862 		    strerror(errno));
863 		return -1;
864 	}
865 	/* Set the groups while the group file is still available */
866 	if (initgroups(pwd->pw_name, pwd->pw_gid) < 0) {
867 		jail_warnx(j, "initgroups %s: %s", pwd->pw_name,
868 		    strerror(errno));
869 		return -1;
870 	}
871 	return 0;
872 }
873 
874 /*
875  * Make sure a mount or consolelog path is a valid absolute pathname
876  * with no symlinks.
877  */
878 static int
879 check_path(struct cfjail *j, const char *pname, const char *path, int isfile,
880     const char *umount_type)
881 {
882 	struct stat st, mpst;
883 	struct statfs stfs;
884 	char *tpath, *p;
885 	const char *jailpath;
886 	size_t jplen;
887 
888 	if (path[0] != '/') {
889 		jail_warnx(j, "%s: %s: not an absolute pathname",
890 		    pname, path);
891 		return -1;
892 	}
893 	/*
894 	 * Only check for symlinks in components below the jail's path,
895 	 * since that's where the security risk lies.
896 	 */
897 	jailpath = string_param(j->intparams[KP_PATH]);
898 	if (jailpath == NULL)
899 		jailpath = "";
900 	jplen = strlen(jailpath);
901 	if (!strncmp(path, jailpath, jplen) && path[jplen] == '/') {
902 		tpath = alloca(strlen(path) + 1);
903 		strcpy(tpath, path);
904 		for (p = tpath + jplen; p != NULL; ) {
905 			p = strchr(p + 1, '/');
906 			if (p)
907 				*p = '\0';
908 			if (lstat(tpath, &st) < 0) {
909 				if (errno == ENOENT && isfile && !p)
910 					break;
911 				jail_warnx(j, "%s: %s: %s", pname, tpath,
912 				    strerror(errno));
913 				return -1;
914 			}
915 			if (S_ISLNK(st.st_mode)) {
916 				jail_warnx(j, "%s: %s is a symbolic link",
917 				    pname, tpath);
918 				return -1;
919 			}
920 			if (p)
921 				*p = '/';
922 		}
923 	}
924 	if (umount_type != NULL) {
925 		if (stat(path, &st) < 0 || statfs(path, &stfs) < 0) {
926 			jail_warnx(j, "%s: %s: %s", pname, path,
927 			    strerror(errno));
928 			return -1;
929 		}
930 		if (stat(stfs.f_mntonname, &mpst) < 0) {
931 			jail_warnx(j, "%s: %s: %s", pname, stfs.f_mntonname,
932 			    strerror(errno));
933 			return -1;
934 		}
935 		if (st.st_ino != mpst.st_ino) {
936 			jail_warnx(j, "%s: %s: not a mount point",
937 			    pname, path);
938 			return -1;
939 		}
940 		if (strcmp(stfs.f_fstypename, umount_type)) {
941 			jail_warnx(j, "%s: %s: not a %s mount",
942 			    pname, path, umount_type);
943 			return -1;
944 		}
945 	}
946 	return 0;
947 }
948