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 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);
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;
91 int create_failed, stopping;
94 requeue(j, &runnable);
97 create_failed = (j->flags & (JF_STOP | JF_FAILED)) == JF_FAILED;
98 stopping = (j->flags & JF_STOP) != 0;
99 comparam = *j->comparam;
101 if (j->comstring == NULL) {
102 j->comparam += create_failed ? -1 : 1;
103 switch ((comparam = *j->comparam)) {
107 if (!bool_param(j->intparams[IP_MOUNT_DEVFS]))
111 case IP_STOP_TIMEOUT:
112 j->comstring = &dummystring;
115 if (j->intparams[comparam] == NULL)
117 j->comstring = create_failed || (stopping &&
118 (j->intparams[comparam]->flags & PF_REV))
119 ? TAILQ_LAST(&j->intparams[comparam]->val,
121 : TAILQ_FIRST(&j->intparams[comparam]->val);
124 j->comstring = j->comstring == &dummystring ? NULL :
125 create_failed || (stopping &&
126 (j->intparams[comparam]->flags & PF_REV))
127 ? TAILQ_PREV(j->comstring, cfstrings, tq)
128 : TAILQ_NEXT(j->comstring, tq);
130 if (j->comstring == NULL || j->comstring->len == 0 ||
131 (create_failed && (comparam == IP_EXEC_PRESTART ||
132 comparam == IP_EXEC_START || comparam == IP_COMMAND ||
133 comparam == IP_EXEC_POSTSTART)))
135 switch (run_command(j)) {
146 * Check command exit status
149 finish_command(struct cfjail *j)
153 if (!(j->flags & JF_SLEEPQ))
155 j->flags &= ~JF_SLEEPQ;
156 if (*j->comparam == IP_STOP_TIMEOUT)
158 j->flags &= ~JF_TIMEOUT;
163 if (!TAILQ_EMPTY(&runnable))
164 requeue(TAILQ_FIRST(&runnable), &ready);
166 if (j->flags & JF_TIMEOUT) {
167 j->flags &= ~JF_TIMEOUT;
168 if (*j->comparam != IP_STOP_TIMEOUT) {
169 jail_warnx(j, "%s: timed out", j->comline);
172 } else if (verbose > 0)
173 jail_note(j, "timed out\n");
174 } else if (j->pstatus != 0) {
175 if (WIFSIGNALED(j->pstatus))
176 jail_warnx(j, "%s: exited on signal %d",
177 j->comline, WTERMSIG(j->pstatus));
179 jail_warnx(j, "%s: failed", j->comline);
190 * Check for finished processes or timeouts.
193 next_proc(int nonblock)
197 struct timespec *tsp;
200 if (!TAILQ_EMPTY(&sleeping)) {
203 if ((j = TAILQ_FIRST(&sleeping)) && j->timeout.tv_sec) {
204 clock_gettime(CLOCK_REALTIME, &ts);
205 ts.tv_sec = j->timeout.tv_sec - ts.tv_sec;
206 ts.tv_nsec = j->timeout.tv_nsec - ts.tv_nsec;
207 if (ts.tv_nsec < 0) {
209 ts.tv_nsec += 1000000000;
212 (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
213 j->flags |= JF_TIMEOUT;
224 switch (kevent(kq, NULL, 0, &ke, 1, tsp)) {
231 j = TAILQ_FIRST(&sleeping);
232 j->flags |= JF_TIMEOUT;
238 (void)waitpid(ke.ident, NULL, WNOHANG);
239 if ((j = find_proc(ke.ident))) {
240 j->pstatus = ke.data;
250 * Run a single command for a jail, possible inside the jail.
253 run_command(struct cfjail *j)
255 const struct passwd *pwd;
256 const struct cfstring *comstring, *s;
259 char *cs, *comcs, *devpath;
260 const char *jidstr, *conslog, *path, *ruleset, *term, *username;
261 enum intparam comparam;
264 int argc, bg, clean, consfd, down, fib, i, injail, sjuser, timeout;
265 #if defined(INET) || defined(INET6)
269 static char *cleanenv;
271 /* Perform some operations that aren't actually commands */
272 comparam = *j->comparam;
273 down = j->flags & (JF_STOP | JF_FAILED);
275 case IP_STOP_TIMEOUT:
276 return term_procs(j);
280 if (jail_remove(j->jid) < 0 && errno == EPERM) {
281 jail_warnx(j, "jail_remove: %s",
285 if (verbose > 0 || (verbose == 0 && (j->flags & JF_STOP
286 ? note_remove : j->name != NULL)))
287 jail_note(j, "removed\n");
289 if (j->flags & JF_STOP)
290 dep_done(j, DF_LIGHT);
292 j->flags &= ~JF_PERSIST;
294 if (create_jail(j) < 0)
297 printf("%d\n", j->jid);
298 if (verbose >= 0 && (j->name || verbose > 0))
299 jail_note(j, "created\n");
300 dep_done(j, DF_LIGHT);
307 * Collect exec arguments. Internal commands for network and
308 * mounting build their own argument lists.
310 comstring = j->comstring;
315 argv = alloca(8 * sizeof(char *));
316 *(const char **)&argv[0] = _PATH_IFCONFIG;
317 if ((cs = strchr(comstring->s, '|'))) {
318 argv[1] = alloca(cs - comstring->s + 1);
319 strlcpy(argv[1], comstring->s, cs - comstring->s + 1);
322 *(const char **)&argv[1] =
323 string_param(j->intparams[IP_INTERFACE]);
326 *(const char **)&argv[2] = "inet";
327 if (!(cs = strchr(addr, '/'))) {
329 *(const char **)&argv[4] = "netmask";
330 *(const char **)&argv[5] = "255.255.255.255";
332 } else if (strchr(cs + 1, '.')) {
333 argv[3] = alloca(cs - addr + 1);
334 strlcpy(argv[3], addr, cs - addr + 1);
335 *(const char **)&argv[4] = "netmask";
336 *(const char **)&argv[5] = cs + 1;
342 *(const char **)&argv[argc] = down ? "-alias" : "alias";
343 argv[argc + 1] = NULL;
349 argv = alloca(8 * sizeof(char *));
350 *(const char **)&argv[0] = _PATH_IFCONFIG;
351 if ((cs = strchr(comstring->s, '|'))) {
352 argv[1] = alloca(cs - comstring->s + 1);
353 strlcpy(argv[1], comstring->s, cs - comstring->s + 1);
356 *(const char **)&argv[1] =
357 string_param(j->intparams[IP_INTERFACE]);
360 *(const char **)&argv[2] = "inet6";
362 if (!(cs = strchr(addr, '/'))) {
363 *(const char **)&argv[4] = "prefixlen";
364 *(const char **)&argv[5] = "128";
368 *(const char **)&argv[argc] = down ? "-alias" : "alias";
369 argv[argc + 1] = NULL;
373 case IP_VNET_INTERFACE:
374 argv = alloca(5 * sizeof(char *));
375 *(const char **)&argv[0] = _PATH_IFCONFIG;
376 argv[1] = comstring->s;
377 *(const char **)&argv[2] = down ? "-vnet" : "vnet";
378 jidstr = string_param(j->intparams[KP_JID]);
379 *(const char **)&argv[3] =
380 jidstr ? jidstr : string_param(j->intparams[KP_NAME]);
385 case IP__MOUNT_FROM_FSTAB:
386 argv = alloca(8 * sizeof(char *));
387 comcs = alloca(comstring->len + 1);
388 strcpy(comcs, comstring->s);
390 for (cs = strtok(comcs, " \t\f\v\r\n"); cs && argc < 4;
391 cs = strtok(NULL, " \t\f\v\r\n"))
396 jail_warnx(j, "%s: %s: missing information",
397 j->intparams[comparam]->name, comstring->s);
400 if (check_path(j, j->intparams[comparam]->name, argv[1], 0,
401 down ? argv[2] : NULL) < 0)
406 *(const char **)&argv[0] = "/sbin/umount";
413 *(const char **)&argv[3] = "-o";
419 *(const char **)&argv[0] = _PATH_MOUNT;
421 *(const char **)&argv[1] = "-t";
425 argv = alloca(7 * sizeof(char *));
426 path = string_param(j->intparams[KP_PATH]);
428 jail_warnx(j, "mount.devfs: no path");
431 devpath = alloca(strlen(path) + 5);
432 sprintf(devpath, "%s/dev", path);
433 if (check_path(j, "mount.devfs", devpath, 0,
434 down ? "devfs" : NULL) < 0)
437 *(const char **)&argv[0] = "/sbin/umount";
441 *(const char **)&argv[0] = _PATH_MOUNT;
442 *(const char **)&argv[1] = "-t";
443 *(const char **)&argv[2] = "devfs";
444 ruleset = string_param(j->intparams[KP_DEVFS_RULESET]);
446 ruleset = "4"; /* devfsrules_jail */
447 argv[3] = alloca(11 + strlen(ruleset));
448 sprintf(argv[3], "-oruleset=%s", ruleset);
449 *(const char **)&argv[4] = ".";
457 goto default_command;
459 TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
461 argv = alloca((argc + 1) * sizeof(char *));
463 TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
466 j->comstring = &dummystring;
471 if ((cs = strpbrk(comstring->s, "!\"$&'()*;<>?[\\]`{|}~")) &&
472 !(cs[0] == '&' && cs[1] == '\0')) {
473 argv = alloca(4 * sizeof(char *));
474 *(const char **)&argv[0] = _PATH_BSHELL;
475 *(const char **)&argv[1] = "-c";
476 argv[2] = comstring->s;
483 comcs = alloca(comstring->len + 1);
484 strcpy(comcs, comstring->s);
486 for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
487 cs = strtok(NULL, " \t\f\v\r\n"))
489 argv = alloca((argc + 1) * sizeof(char *));
490 strcpy(comcs, comstring->s);
492 for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
493 cs = strtok(NULL, " \t\f\v\r\n"))
501 if (int_param(j->intparams[IP_EXEC_TIMEOUT], &timeout) &&
503 clock_gettime(CLOCK_REALTIME, &j->timeout);
504 j->timeout.tv_sec += timeout;
506 j->timeout.tv_sec = 0;
508 injail = comparam == IP_EXEC_START || comparam == IP_COMMAND ||
509 comparam == IP_EXEC_STOP;
510 clean = bool_param(j->intparams[IP_EXEC_CLEAN]);
511 username = string_param(j->intparams[injail
512 ? IP_EXEC_JAIL_USER : IP_EXEC_SYSTEM_USER]);
513 sjuser = bool_param(j->intparams[IP_EXEC_SYSTEM_JAIL_USER]);
517 (conslog = string_param(j->intparams[IP_EXEC_CONSOLELOG]))) {
518 if (check_path(j, "exec.consolelog", conslog, 1, NULL) < 0)
521 open(conslog, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE);
523 jail_warnx(j, "open %s: %s", conslog, strerror(errno));
529 for (i = 0; argv[i]; i++)
530 comlen += strlen(argv[i]) + 1;
531 j->comline = cs = emalloc(comlen);
532 for (i = 0; argv[i]; i++) {
535 cs += strlen(argv[i]) + 1;
540 jail_note(j, "run command%s%s%s: %s\n",
541 injail ? " in jail" : "", username ? " as " : "",
542 username ? username : "", j->comline);
548 if (bg || !add_proc(j, pid)) {
560 /* Set up the environment and run the command */
563 if ((clean || username) && injail && sjuser &&
564 get_user_info(j, username, &pwd, &lcap) < 0)
567 /* jail_attach won't chdir along with its chroot. */
568 path = string_param(j->intparams[KP_PATH]);
569 if (path && chdir(path) < 0) {
570 jail_warnx(j, "chdir %s: %s", path, strerror(errno));
573 if (int_param(j->intparams[IP_EXEC_FIB], &fib) &&
575 jail_warnx(j, "setfib: %s", strerror(errno));
578 if (jail_attach(j->jid) < 0) {
579 jail_warnx(j, "jail_attach: %s", strerror(errno));
583 if (clean || username) {
584 if (!(injail && sjuser) &&
585 get_user_info(j, username, &pwd, &lcap) < 0)
588 term = getenv("TERM");
590 setenv("PATH", "/bin:/usr/bin", 0);
592 setenv("TERM", term, 1);
594 if (setusercontext(lcap, pwd, pwd->pw_uid, username
595 ? LOGIN_SETALL & ~LOGIN_SETGROUP & ~LOGIN_SETLOGIN
596 : LOGIN_SETPATH | LOGIN_SETENV) < 0) {
597 jail_warnx(j, "setusercontext %s: %s", pwd->pw_name,
602 setenv("USER", pwd->pw_name, 1);
603 setenv("HOME", pwd->pw_dir, 1);
605 *pwd->pw_shell ? pwd->pw_shell : _PATH_BSHELL, 1);
606 if (clean && chdir(pwd->pw_dir) < 0) {
607 jail_warnx(j, "chdir %s: %s",
608 pwd->pw_dir, strerror(errno));
614 if (consfd != 0 && (dup2(consfd, 1) < 0 || dup2(consfd, 2) < 0)) {
615 jail_warnx(j, "exec.consolelog: %s", strerror(errno));
619 execvp(argv[0], argv);
620 jail_warnx(j, "exec %s: %s", argv[0], strerror(errno));
625 * Add a process to the hash, tied to a jail.
628 add_proc(struct cfjail *j, pid_t pid)
634 if (!kq && (kq = kqueue()) < 0)
636 EV_SET(&ke, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
637 if (kevent(kq, &ke, 1, NULL, 0, NULL) < 0) {
642 ph = emalloc(sizeof(struct phash));
645 LIST_INSERT_HEAD(&phash[pid % PHASH_SIZE], ph, le);
647 j->flags |= JF_SLEEPQ;
648 if (j->timeout.tv_sec == 0)
649 requeue(j, &sleeping);
651 /* File the jail in the sleep queue acording to its timeout. */
652 TAILQ_REMOVE(j->queue, j, tq);
653 TAILQ_FOREACH(tj, &sleeping, tq) {
654 if (!tj->timeout.tv_sec ||
655 j->timeout.tv_sec < tj->timeout.tv_sec ||
656 (j->timeout.tv_sec == tj->timeout.tv_sec &&
657 j->timeout.tv_nsec <= tj->timeout.tv_nsec)) {
658 TAILQ_INSERT_BEFORE(tj, j, tq);
663 TAILQ_INSERT_TAIL(&sleeping, j, tq);
664 j->queue = &sleeping;
670 * Remove any processes from the hash that correspond to a jail.
673 clear_procs(struct cfjail *j)
676 struct phash *ph, *tph;
680 for (i = 0; i < PHASH_SIZE; i++)
681 LIST_FOREACH_SAFE(ph, &phash[i], le, tph)
683 EV_SET(&ke, ph->pid, EVFILT_PROC, EV_DELETE,
685 (void)kevent(kq, &ke, 1, NULL, 0, NULL);
692 * Find the jail that corresponds to an exited process.
694 static struct cfjail *
700 LIST_FOREACH(ph, &phash[pid % PHASH_SIZE], le)
701 if (ph->pid == pid) {
705 return --j->nprocs ? NULL : j;
711 * Send SIGTERM to all processes in a jail and wait for them to die.
714 term_procs(struct cfjail *j)
716 struct kinfo_proc *ki;
717 int i, noted, pcnt, timeout;
721 if (!int_param(j->intparams[IP_STOP_TIMEOUT], &timeout))
722 timeout = DEFAULT_STOP_TIMEOUT;
723 else if (timeout == 0)
727 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
732 ki = kvm_getprocs(kd, KERN_PROC_PROC, 0, &pcnt);
736 for (i = 0; i < pcnt; i++)
737 if (ki[i].ki_jid == j->jid &&
738 kill(ki[i].ki_pid, SIGTERM) == 0) {
739 (void)add_proc(j, ki[i].ki_pid);
743 jail_note(j, "sent SIGTERM to:");
745 printf(" %d", ki[i].ki_pid);
751 clock_gettime(CLOCK_REALTIME, &j->timeout);
752 j->timeout.tv_sec += timeout;
759 * Look up a user in the passwd and login.conf files.
762 get_user_info(struct cfjail *j, const char *username,
763 const struct passwd **pwdp, login_cap_t **lcapp)
765 const struct passwd *pwd;
767 *pwdp = pwd = username ? getpwnam(username) : getpwuid(getuid());
770 jail_warnx(j, "getpwnam%s%s: %s", username ? " " : "",
771 username ? username : "", strerror(errno));
773 jail_warnx(j, "%s: no such user", username);
775 jail_warnx(j, "unknown uid %d", getuid());
778 *lcapp = login_getpwclass(pwd);
779 if (*lcapp == NULL) {
780 jail_warnx(j, "getpwclass %s: %s", pwd->pw_name,
784 /* Set the groups while the group file is still available */
785 if (initgroups(pwd->pw_name, pwd->pw_gid) < 0) {
786 jail_warnx(j, "initgroups %s: %s", pwd->pw_name,
794 * Make sure a mount or consolelog path is a valid absolute pathname
798 check_path(struct cfjail *j, const char *pname, const char *path, int isfile,
799 const char *umount_type)
801 struct stat st, mpst;
804 const char *jailpath;
807 if (path[0] != '/') {
808 jail_warnx(j, "%s: %s: not an absolute pathname",
813 * Only check for symlinks in components below the jail's path,
814 * since that's where the security risk lies.
816 jailpath = string_param(j->intparams[KP_PATH]);
817 if (jailpath == NULL)
819 jplen = strlen(jailpath);
820 if (!strncmp(path, jailpath, jplen) && path[jplen] == '/') {
821 tpath = alloca(strlen(path) + 1);
823 for (p = tpath + jplen; p != NULL; ) {
824 p = strchr(p + 1, '/');
827 if (lstat(tpath, &st) < 0) {
828 if (errno == ENOENT && isfile && !p)
830 jail_warnx(j, "%s: %s: %s", pname, tpath,
834 if (S_ISLNK(st.st_mode)) {
835 jail_warnx(j, "%s: %s is a symbolic link",
843 if (umount_type != NULL) {
844 if (stat(path, &st) < 0 || statfs(path, &stfs) < 0) {
845 jail_warnx(j, "%s: %s: %s", pname, path,
849 if (stat(stfs.f_mntonname, &mpst) < 0) {
850 jail_warnx(j, "%s: %s: %s", pname, stfs.f_mntonname,
854 if (st.st_ino != mpst.st_ino) {
855 jail_warnx(j, "%s: %s: not a mount point",
859 if (strcmp(stfs.f_fstypename, umount_type)) {
860 jail_warnx(j, "%s: %s: not a %s mount",
861 pname, path, umount_type);