2 * Copyright (c) 2011 James Gritton
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/types.h>
31 #include <sys/event.h>
32 #include <sys/mount.h>
34 #include <sys/sysctl.h>
42 #include <login_cap.h>
53 #define DEFAULT_STOP_TIMEOUT 10
54 #define PHASH_SIZE 256
56 LIST_HEAD(phhead, phash);
66 extern char **environ;
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);
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];
85 * Run the next command associated with a jail.
88 next_command(struct cfjail *j)
90 enum intparam comparam;
94 requeue(j, &runnable);
97 create_failed = (j->flags & (JF_STOP | JF_FAILED)) == JF_FAILED;
98 comparam = *j->comparam;
100 if (j->comstring == NULL) {
101 j->comparam += create_failed ? -1 : 1;
102 switch ((comparam = *j->comparam)) {
106 if (!bool_param(j->intparams[IP_MOUNT_DEVFS]))
110 case IP_STOP_TIMEOUT:
111 j->comstring = &dummystring;
114 if (j->intparams[comparam] == NULL)
116 j->comstring = create_failed
117 ? TAILQ_LAST(&j->intparams[comparam]->val,
119 : TAILQ_FIRST(&j->intparams[comparam]->val);
122 j->comstring = j->comstring == &dummystring ? NULL :
124 ? TAILQ_PREV(j->comstring, cfstrings, tq)
125 : TAILQ_NEXT(j->comstring, tq);
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)))
132 switch (run_command(j)) {
143 * Check command exit status
146 finish_command(struct cfjail *j)
150 if (!(j->flags & JF_SLEEPQ))
152 j->flags &= ~JF_SLEEPQ;
153 if (*j->comparam == IP_STOP_TIMEOUT)
155 j->flags &= ~JF_TIMEOUT;
160 if (!TAILQ_EMPTY(&runnable))
161 requeue(TAILQ_FIRST(&runnable), &ready);
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);
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));
176 jail_warnx(j, "%s: failed", j->comline);
187 * Check for finished processes or timeouts.
190 next_proc(int nonblock)
194 struct timespec *tsp;
197 if (!TAILQ_EMPTY(&sleeping)) {
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) {
206 ts.tv_nsec += 1000000000;
209 (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
210 j->flags |= JF_TIMEOUT;
221 switch (kevent(kq, NULL, 0, &ke, 1, tsp)) {
228 j = TAILQ_FIRST(&sleeping);
229 j->flags |= JF_TIMEOUT;
235 (void)waitpid(ke.ident, NULL, WNOHANG);
236 if ((j = find_proc(ke.ident))) {
237 j->pstatus = ke.data;
247 * Run a single command for a jail, possible inside the jail.
250 run_command(struct cfjail *j)
252 const struct passwd *pwd;
253 const struct cfstring *comstring, *s;
256 char *cs, *comcs, *devpath;
257 const char *jidstr, *conslog, *path, *ruleset, *term, *username;
258 enum intparam comparam;
261 int argc, bg, clean, consfd, down, fib, i, injail, sjuser, timeout;
262 #if defined(INET) || defined(INET6)
266 static char *cleanenv;
268 /* Perform some operations that aren't actually commands */
269 comparam = *j->comparam;
270 down = j->flags & (JF_STOP | JF_FAILED);
272 case IP_STOP_TIMEOUT:
273 return term_procs(j);
277 if (jail_remove(j->jid) < 0 && errno == EPERM) {
278 jail_warnx(j, "jail_remove: %s",
282 if (verbose > 0 || (verbose == 0 && (j->flags & JF_STOP
283 ? note_remove : j->name != NULL)))
284 jail_note(j, "removed\n");
286 if (j->flags & JF_STOP)
287 dep_done(j, DF_LIGHT);
289 j->flags &= ~JF_PERSIST;
291 if (create_jail(j) < 0)
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);
304 * Collect exec arguments. Internal commands for network and
305 * mounting build their own argument lists.
307 comstring = j->comstring;
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);
319 *(const char **)&argv[1] =
320 string_param(j->intparams[IP_INTERFACE]);
323 *(const char **)&argv[2] = "inet";
324 if (!(cs = strchr(addr, '/'))) {
326 *(const char **)&argv[4] = "netmask";
327 *(const char **)&argv[5] = "255.255.255.255";
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;
339 *(const char **)&argv[argc] = down ? "-alias" : "alias";
340 argv[argc + 1] = NULL;
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);
353 *(const char **)&argv[1] =
354 string_param(j->intparams[IP_INTERFACE]);
357 *(const char **)&argv[2] = "inet6";
359 if (!(cs = strchr(addr, '/'))) {
360 *(const char **)&argv[4] = "prefixlen";
361 *(const char **)&argv[5] = "128";
365 *(const char **)&argv[argc] = down ? "-alias" : "alias";
366 argv[argc + 1] = NULL;
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]);
382 case IP__MOUNT_FROM_FSTAB:
383 argv = alloca(8 * sizeof(char *));
384 comcs = alloca(comstring->len + 1);
385 strcpy(comcs, comstring->s);
387 for (cs = strtok(comcs, " \t\f\v\r\n"); cs && argc < 4;
388 cs = strtok(NULL, " \t\f\v\r\n"))
393 jail_warnx(j, "%s: %s: missing information",
394 j->intparams[comparam]->name, comstring->s);
397 if (check_path(j, j->intparams[comparam]->name, argv[1], 0,
398 down ? argv[2] : NULL) < 0)
403 *(const char **)&argv[0] = "/sbin/umount";
410 *(const char **)&argv[3] = "-o";
416 *(const char **)&argv[0] = _PATH_MOUNT;
418 *(const char **)&argv[1] = "-t";
422 argv = alloca(7 * sizeof(char *));
423 path = string_param(j->intparams[KP_PATH]);
425 jail_warnx(j, "mount.devfs: no path");
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)
434 *(const char **)&argv[0] = "/sbin/umount";
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]);
443 ruleset = "4"; /* devfsrules_jail */
444 argv[3] = alloca(11 + strlen(ruleset));
445 sprintf(argv[3], "-oruleset=%s", ruleset);
446 *(const char **)&argv[4] = ".";
454 goto default_command;
456 TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
458 argv = alloca((argc + 1) * sizeof(char *));
460 TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
463 j->comstring = &dummystring;
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;
480 comcs = alloca(comstring->len + 1);
481 strcpy(comcs, comstring->s);
483 for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
484 cs = strtok(NULL, " \t\f\v\r\n"))
486 argv = alloca((argc + 1) * sizeof(char *));
487 strcpy(comcs, comstring->s);
489 for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
490 cs = strtok(NULL, " \t\f\v\r\n"))
498 if (int_param(j->intparams[IP_EXEC_TIMEOUT], &timeout) &&
500 clock_gettime(CLOCK_REALTIME, &j->timeout);
501 j->timeout.tv_sec += timeout;
503 j->timeout.tv_sec = 0;
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]);
514 (conslog = string_param(j->intparams[IP_EXEC_CONSOLELOG]))) {
515 if (check_path(j, "exec.consolelog", conslog, 1, NULL) < 0)
518 open(conslog, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE);
520 jail_warnx(j, "open %s: %s", conslog, strerror(errno));
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++) {
532 cs += strlen(argv[i]) + 1;
537 jail_note(j, "run command%s%s%s: %s\n",
538 injail ? " in jail" : "", username ? " as " : "",
539 username ? username : "", j->comline);
558 /* Set up the environment and run the command */
561 if ((clean || username) && injail && sjuser &&
562 get_user_info(j, username, &pwd, &lcap) < 0)
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));
571 if (int_param(j->intparams[IP_EXEC_FIB], &fib) &&
573 jail_warnx(j, "setfib: %s", strerror(errno));
576 if (jail_attach(j->jid) < 0) {
577 jail_warnx(j, "jail_attach: %s", strerror(errno));
581 if (clean || username) {
582 if (!(injail && sjuser) &&
583 get_user_info(j, username, &pwd, &lcap) < 0)
586 term = getenv("TERM");
588 setenv("PATH", "/bin:/usr/bin", 0);
590 setenv("TERM", term, 1);
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,
600 setenv("USER", pwd->pw_name, 1);
601 setenv("HOME", pwd->pw_dir, 1);
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));
612 if (consfd != 0 && (dup2(consfd, 1) < 0 || dup2(consfd, 2) < 0)) {
613 jail_warnx(j, "exec.consolelog: %s", strerror(errno));
617 execvp(argv[0], argv);
618 jail_warnx(j, "exec %s: %s", argv[0], strerror(errno));
623 * Add a process to the hash, tied to a jail.
626 add_proc(struct cfjail *j, pid_t pid)
632 if (!kq && (kq = kqueue()) < 0)
634 EV_SET(&ke, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
635 if (kevent(kq, &ke, 1, NULL, 0, NULL) < 0)
637 ph = emalloc(sizeof(struct phash));
640 LIST_INSERT_HEAD(&phash[pid % PHASH_SIZE], ph, le);
642 j->flags |= JF_SLEEPQ;
643 if (j->timeout.tv_sec == 0)
644 requeue(j, &sleeping);
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);
658 TAILQ_INSERT_TAIL(&sleeping, j, tq);
659 j->queue = &sleeping;
664 * Remove any processes from the hash that correspond to a jail.
667 clear_procs(struct cfjail *j)
670 struct phash *ph, *tph;
674 for (i = 0; i < PHASH_SIZE; i++)
675 LIST_FOREACH_SAFE(ph, &phash[i], le, tph)
677 EV_SET(&ke, ph->pid, EVFILT_PROC, EV_DELETE,
679 (void)kevent(kq, &ke, 1, NULL, 0, NULL);
686 * Find the jail that corresponds to an exited process.
688 static struct cfjail *
694 LIST_FOREACH(ph, &phash[pid % PHASH_SIZE], le)
695 if (ph->pid == pid) {
699 return --j->nprocs ? NULL : j;
705 * Send SIGTERM to all processes in a jail and wait for them to die.
708 term_procs(struct cfjail *j)
710 struct kinfo_proc *ki;
711 int i, noted, pcnt, timeout;
715 if (!int_param(j->intparams[IP_STOP_TIMEOUT], &timeout))
716 timeout = DEFAULT_STOP_TIMEOUT;
717 else if (timeout == 0)
721 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
726 ki = kvm_getprocs(kd, KERN_PROC_PROC, 0, &pcnt);
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);
737 jail_note(j, "sent SIGTERM to:");
739 printf(" %d", ki[i].ki_pid);
745 clock_gettime(CLOCK_REALTIME, &j->timeout);
746 j->timeout.tv_sec += timeout;
753 * Look up a user in the passwd and login.conf files.
756 get_user_info(struct cfjail *j, const char *username,
757 const struct passwd **pwdp, login_cap_t **lcapp)
759 const struct passwd *pwd;
761 *pwdp = pwd = username ? getpwnam(username) : getpwuid(getuid());
764 jail_warnx(j, "getpwnam%s%s: %s", username ? " " : "",
765 username ? username : "", strerror(errno));
767 jail_warnx(j, "%s: no such user", username);
769 jail_warnx(j, "unknown uid %d", getuid());
772 *lcapp = login_getpwclass(pwd);
773 if (*lcapp == NULL) {
774 jail_warnx(j, "getpwclass %s: %s", pwd->pw_name,
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,
788 * Make sure a mount or consolelog path is a valid absolute pathname
792 check_path(struct cfjail *j, const char *pname, const char *path, int isfile,
793 const char *umount_type)
795 struct stat st, mpst;
798 const char *jailpath;
801 if (path[0] != '/') {
802 jail_warnx(j, "%s: %s: not an absolute pathname",
807 * Only check for symlinks in components below the jail's path,
808 * since that's where the security risk lies.
810 jailpath = string_param(j->intparams[KP_PATH]);
811 if (jailpath == NULL)
813 jplen = strlen(jailpath);
814 if (!strncmp(path, jailpath, jplen) && path[jplen] == '/') {
815 tpath = alloca(strlen(path) + 1);
817 for (p = tpath + jplen; p != NULL; ) {
818 p = strchr(p + 1, '/');
821 if (lstat(tpath, &st) < 0) {
822 if (errno == ENOENT && isfile && !p)
824 jail_warnx(j, "%s: %s: %s", pname, tpath,
828 if (S_ISLNK(st.st_mode)) {
829 jail_warnx(j, "%s: %s is a symbolic link",
837 if (umount_type != NULL) {
838 if (stat(path, &st) < 0 || statfs(path, &stfs) < 0) {
839 jail_warnx(j, "%s: %s: %s", pname, path,
843 if (stat(stfs.f_mntonname, &mpst) < 0) {
844 jail_warnx(j, "%s: %s: %s", pname, stfs.f_mntonname,
848 if (st.st_ino != mpst.st_ino) {
849 jail_warnx(j, "%s: %s: not a mount point",
853 if (strcmp(stfs.f_fstypename, umount_type)) {
854 jail_warnx(j, "%s: %s: not a %s mount",
855 pname, path, umount_type);