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>
54 #define DEFAULT_STOP_TIMEOUT 10
55 #define PHASH_SIZE 256
57 LIST_HEAD(phhead, phash);
67 extern char **environ;
69 static int run_command(struct cfjail *j);
70 static int add_proc(struct cfjail *j, pid_t pid);
71 static void clear_procs(struct cfjail *j);
72 static struct cfjail *find_proc(pid_t pid);
73 static int term_procs(struct cfjail *j);
74 static int get_user_info(struct cfjail *j, const char *username,
75 const struct passwd **pwdp, login_cap_t **lcapp);
76 static int check_path(struct cfjail *j, const char *pname, const char *path,
77 int isfile, const char *umount_type);
79 static struct cfjails sleeping = TAILQ_HEAD_INITIALIZER(sleeping);
80 static struct cfjails runnable = TAILQ_HEAD_INITIALIZER(runnable);
81 static struct cfstring dummystring = { .len = 1 };
82 static struct phhead phash[PHASH_SIZE];
86 * Run the next command associated with a jail.
89 next_command(struct cfjail *j)
91 enum intparam comparam;
92 int create_failed, stopping;
95 if (j->flags & JF_FROM_RUNQ)
96 requeue_head(j, &runnable);
98 requeue(j, &runnable);
101 j->flags &= ~JF_FROM_RUNQ;
102 create_failed = (j->flags & (JF_STOP | JF_FAILED)) == JF_FAILED;
103 stopping = (j->flags & JF_STOP) != 0;
104 comparam = *j->comparam;
106 if (j->comstring == NULL) {
107 j->comparam += create_failed ? -1 : 1;
108 switch ((comparam = *j->comparam)) {
112 if (!bool_param(j->intparams[IP_MOUNT_DEVFS]))
114 j->comstring = &dummystring;
116 case IP_MOUNT_FDESCFS:
117 if (!bool_param(j->intparams[IP_MOUNT_FDESCFS]))
119 j->comstring = &dummystring;
121 case IP_MOUNT_PROCFS:
122 if (!bool_param(j->intparams[IP_MOUNT_PROCFS]))
124 j->comstring = &dummystring;
127 case IP_STOP_TIMEOUT:
128 j->comstring = &dummystring;
131 if (j->intparams[comparam] == NULL)
133 j->comstring = create_failed || (stopping &&
134 (j->intparams[comparam]->flags & PF_REV))
135 ? TAILQ_LAST(&j->intparams[comparam]->val,
137 : TAILQ_FIRST(&j->intparams[comparam]->val);
140 j->comstring = j->comstring == &dummystring ? NULL :
141 create_failed || (stopping &&
142 (j->intparams[comparam]->flags & PF_REV))
143 ? TAILQ_PREV(j->comstring, cfstrings, tq)
144 : TAILQ_NEXT(j->comstring, tq);
146 if (j->comstring == NULL || j->comstring->len == 0 ||
147 (create_failed && (comparam == IP_EXEC_PRESTART ||
148 comparam == IP_EXEC_START || comparam == IP_COMMAND ||
149 comparam == IP_EXEC_POSTSTART)))
151 switch (run_command(j)) {
162 * Check command exit status
165 finish_command(struct cfjail *j)
170 if (!(j->flags & JF_SLEEPQ))
172 j->flags &= ~JF_SLEEPQ;
173 if (*j->comparam == IP_STOP_TIMEOUT) {
174 j->flags &= ~JF_TIMEOUT;
179 if (!TAILQ_EMPTY(&runnable)) {
180 rj = TAILQ_FIRST(&runnable);
181 rj->flags |= JF_FROM_RUNQ;
185 if (j->flags & JF_TIMEOUT) {
186 j->flags &= ~JF_TIMEOUT;
187 if (*j->comparam != IP_STOP_TIMEOUT) {
188 jail_warnx(j, "%s: timed out", j->comline);
191 } else if (verbose > 0)
192 jail_note(j, "timed out\n");
193 } else if (j->pstatus != 0) {
194 if (WIFSIGNALED(j->pstatus))
195 jail_warnx(j, "%s: exited on signal %d",
196 j->comline, WTERMSIG(j->pstatus));
198 jail_warnx(j, "%s: failed", j->comline);
209 * Check for finished processes or timeouts.
212 next_proc(int nonblock)
216 struct timespec *tsp;
219 if (!TAILQ_EMPTY(&sleeping)) {
222 if ((j = TAILQ_FIRST(&sleeping)) && j->timeout.tv_sec) {
223 clock_gettime(CLOCK_REALTIME, &ts);
224 ts.tv_sec = j->timeout.tv_sec - ts.tv_sec;
225 ts.tv_nsec = j->timeout.tv_nsec - ts.tv_nsec;
226 if (ts.tv_nsec < 0) {
228 ts.tv_nsec += 1000000000;
231 (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
232 j->flags |= JF_TIMEOUT;
243 switch (kevent(kq, NULL, 0, &ke, 1, tsp)) {
250 j = TAILQ_FIRST(&sleeping);
251 j->flags |= JF_TIMEOUT;
257 (void)waitpid(ke.ident, NULL, WNOHANG);
258 if ((j = find_proc(ke.ident))) {
259 j->pstatus = ke.data;
269 * Run a single command for a jail, possibly inside the jail.
272 run_command(struct cfjail *j)
274 const struct passwd *pwd;
275 const struct cfstring *comstring, *s;
278 char *acs, *cs, *comcs, *devpath;
279 const char *jidstr, *conslog, *path, *ruleset, *term, *username;
280 enum intparam comparam;
283 int argc, bg, clean, consfd, down, fib, i, injail, sjuser, timeout;
284 #if defined(INET) || defined(INET6)
285 char *addr, *extrap, *p, *val;
288 static char *cleanenv;
290 /* Perform some operations that aren't actually commands */
291 comparam = *j->comparam;
292 down = j->flags & (JF_STOP | JF_FAILED);
294 case IP_STOP_TIMEOUT:
295 return term_procs(j);
299 if (jail_remove(j->jid) < 0 && errno == EPERM) {
300 jail_warnx(j, "jail_remove: %s",
304 if (verbose > 0 || (verbose == 0 && (j->flags & JF_STOP
305 ? note_remove : j->name != NULL)))
306 jail_note(j, "removed\n");
308 if (j->flags & JF_STOP)
309 dep_done(j, DF_LIGHT);
311 j->flags &= ~JF_PERSIST;
313 if (create_jail(j) < 0)
316 printf("%d\n", j->jid);
317 if (verbose >= 0 && (j->name || verbose > 0))
318 jail_note(j, "created\n");
319 dep_done(j, DF_LIGHT);
326 * Collect exec arguments. Internal commands for network and
327 * mounting build their own argument lists.
329 comstring = j->comstring;
335 val = alloca(strlen(comstring->s) + 1);
336 strcpy(val, comstring->s);
339 while ((p = strchr(cs, ' ')) != NULL && strlen(p) > 1) {
340 if (extrap == NULL) {
348 argv = alloca((8 + argc) * sizeof(char *));
349 argv[0] = _PATH_IFCONFIG;
350 if ((cs = strchr(val, '|'))) {
351 argv[1] = acs = alloca(cs - val + 1);
352 strlcpy(acs, val, cs - val + 1);
355 argv[1] = string_param(j->intparams[IP_INTERFACE]);
359 if (!(cs = strchr(addr, '/'))) {
362 argv[5] = "255.255.255.255";
364 } else if (strchr(cs + 1, '.')) {
365 argv[3] = acs = alloca(cs - addr + 1);
366 strlcpy(acs, addr, cs - addr + 1);
376 for (cs = strtok(extrap, " "); cs;
377 cs = strtok(NULL, " ")) {
378 size_t len = strlen(cs) + 1;
379 argv[argc++] = acs = alloca(len);
380 strlcpy(acs, cs, len);
384 argv[argc] = down ? "-alias" : "alias";
385 argv[argc + 1] = NULL;
392 val = alloca(strlen(comstring->s) + 1);
393 strcpy(val, comstring->s);
396 while ((p = strchr(cs, ' ')) != NULL && strlen(p) > 1) {
397 if (extrap == NULL) {
405 argv = alloca((8 + argc) * sizeof(char *));
406 argv[0] = _PATH_IFCONFIG;
407 if ((cs = strchr(val, '|'))) {
408 argv[1] = acs = alloca(cs - val + 1);
409 strlcpy(acs, val, cs - val + 1);
412 argv[1] = string_param(j->intparams[IP_INTERFACE]);
417 if (!(cs = strchr(addr, '/'))) {
418 argv[4] = "prefixlen";
425 for (cs = strtok(extrap, " "); cs;
426 cs = strtok(NULL, " ")) {
427 size_t len = strlen(cs) + 1;
428 argv[argc++] = acs = alloca(len);
429 strlcpy(acs, cs, len);
433 argv[argc] = down ? "-alias" : "alias";
434 argv[argc + 1] = NULL;
438 case IP_VNET_INTERFACE:
439 argv = alloca(5 * sizeof(char *));
440 argv[0] = _PATH_IFCONFIG;
441 argv[1] = comstring->s;
442 argv[2] = down ? "-vnet" : "vnet";
443 jidstr = string_param(j->intparams[KP_JID]);
444 argv[3] = jidstr ? jidstr : string_param(j->intparams[KP_NAME]);
449 case IP__MOUNT_FROM_FSTAB:
450 argv = alloca(8 * sizeof(char *));
451 comcs = alloca(comstring->len + 1);
452 strcpy(comcs, comstring->s);
454 for (cs = strtok(comcs, " \t\f\v\r\n"); cs && argc < 4;
455 cs = strtok(NULL, " \t\f\v\r\n")) {
456 if (argc <= 1 && strunvis(cs, cs) < 0) {
457 jail_warnx(j, "%s: %s: fstab parse error",
458 j->intparams[comparam]->name, comstring->s);
466 jail_warnx(j, "%s: %s: missing information",
467 j->intparams[comparam]->name, comstring->s);
470 if (check_path(j, j->intparams[comparam]->name, argv[1], 0,
471 down ? argv[2] : NULL) < 0)
476 argv[0] = "/sbin/umount";
489 argv[0] = _PATH_MOUNT;
495 argv = alloca(7 * sizeof(char *));
496 path = string_param(j->intparams[KP_PATH]);
498 jail_warnx(j, "mount.devfs: no path");
501 devpath = alloca(strlen(path) + 5);
502 sprintf(devpath, "%s/dev", path);
503 if (check_path(j, "mount.devfs", devpath, 0,
504 down ? "devfs" : NULL) < 0)
507 argv[0] = "/sbin/umount";
511 argv[0] = _PATH_MOUNT;
514 ruleset = string_param(j->intparams[KP_DEVFS_RULESET]);
516 ruleset = "4"; /* devfsrules_jail */
517 argv[3] = acs = alloca(11 + strlen(ruleset));
518 sprintf(acs, "-oruleset=%s", ruleset);
525 case IP_MOUNT_FDESCFS:
526 argv = alloca(7 * sizeof(char *));
527 path = string_param(j->intparams[KP_PATH]);
529 jail_warnx(j, "mount.fdescfs: no path");
532 devpath = alloca(strlen(path) + 8);
533 sprintf(devpath, "%s/dev/fd", path);
534 if (check_path(j, "mount.fdescfs", devpath, 0,
535 down ? "fdescfs" : NULL) < 0)
538 argv[0] = "/sbin/umount";
542 argv[0] = _PATH_MOUNT;
551 case IP_MOUNT_PROCFS:
552 argv = alloca(7 * sizeof(char *));
553 path = string_param(j->intparams[KP_PATH]);
555 jail_warnx(j, "mount.procfs: no path");
558 devpath = alloca(strlen(path) + 6);
559 sprintf(devpath, "%s/proc", path);
560 if (check_path(j, "mount.procfs", devpath, 0,
561 down ? "procfs" : NULL) < 0)
564 argv[0] = "/sbin/umount";
568 argv[0] = _PATH_MOUNT;
579 goto default_command;
581 TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
583 argv = alloca((argc + 1) * sizeof(char *));
585 TAILQ_FOREACH(s, &j->intparams[IP_COMMAND]->val, tq)
588 j->comstring = &dummystring;
593 if ((cs = strpbrk(comstring->s, "!\"$&'()*;<>?[\\]`{|}~")) &&
594 !(cs[0] == '&' && cs[1] == '\0')) {
595 argv = alloca(4 * sizeof(char *));
596 argv[0] = _PATH_BSHELL;
598 argv[2] = comstring->s;
605 comcs = alloca(comstring->len + 1);
606 strcpy(comcs, comstring->s);
608 for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
609 cs = strtok(NULL, " \t\f\v\r\n"))
611 argv = alloca((argc + 1) * sizeof(char *));
612 strcpy(comcs, comstring->s);
614 for (cs = strtok(comcs, " \t\f\v\r\n"); cs;
615 cs = strtok(NULL, " \t\f\v\r\n"))
623 if (int_param(j->intparams[IP_EXEC_TIMEOUT], &timeout) &&
625 clock_gettime(CLOCK_REALTIME, &j->timeout);
626 j->timeout.tv_sec += timeout;
628 j->timeout.tv_sec = 0;
630 injail = comparam == IP_EXEC_START || comparam == IP_COMMAND ||
631 comparam == IP_EXEC_STOP;
632 clean = bool_param(j->intparams[IP_EXEC_CLEAN]);
633 username = string_param(j->intparams[injail
634 ? IP_EXEC_JAIL_USER : IP_EXEC_SYSTEM_USER]);
635 sjuser = bool_param(j->intparams[IP_EXEC_SYSTEM_JAIL_USER]);
639 (conslog = string_param(j->intparams[IP_EXEC_CONSOLELOG]))) {
640 if (check_path(j, "exec.consolelog", conslog, 1, NULL) < 0)
643 open(conslog, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE);
645 jail_warnx(j, "open %s: %s", conslog, strerror(errno));
651 for (i = 0; argv[i]; i++)
652 comlen += strlen(argv[i]) + 1;
653 j->comline = cs = emalloc(comlen);
654 for (i = 0; argv[i]; i++) {
657 cs += strlen(argv[i]) + 1;
662 jail_note(j, "run command%s%s%s: %s\n",
663 injail ? " in jail" : "", username ? " as " : "",
664 username ? username : "", j->comline);
670 if (bg || !add_proc(j, pid)) {
682 /* Set up the environment and run the command */
685 if ((clean || username) && injail && sjuser &&
686 get_user_info(j, username, &pwd, &lcap) < 0)
689 /* jail_attach won't chdir along with its chroot. */
690 path = string_param(j->intparams[KP_PATH]);
691 if (path && chdir(path) < 0) {
692 jail_warnx(j, "chdir %s: %s", path, strerror(errno));
695 if (int_param(j->intparams[IP_EXEC_FIB], &fib) &&
697 jail_warnx(j, "setfib: %s", strerror(errno));
700 if (jail_attach(j->jid) < 0) {
701 jail_warnx(j, "jail_attach: %s", strerror(errno));
705 if (clean || username) {
706 if (!(injail && sjuser) &&
707 get_user_info(j, username, &pwd, &lcap) < 0)
710 term = getenv("TERM");
712 setenv("PATH", "/bin:/usr/bin", 0);
714 setenv("TERM", term, 1);
716 if (setgid(pwd->pw_gid) < 0) {
717 jail_warnx(j, "setgid %d: %s", pwd->pw_gid,
721 if (setusercontext(lcap, pwd, pwd->pw_uid, username
722 ? LOGIN_SETALL & ~LOGIN_SETGROUP & ~LOGIN_SETLOGIN
723 : LOGIN_SETPATH | LOGIN_SETENV) < 0) {
724 jail_warnx(j, "setusercontext %s: %s", pwd->pw_name,
729 setenv("USER", pwd->pw_name, 1);
730 setenv("HOME", pwd->pw_dir, 1);
732 *pwd->pw_shell ? pwd->pw_shell : _PATH_BSHELL, 1);
733 if (clean && chdir(pwd->pw_dir) < 0) {
734 jail_warnx(j, "chdir %s: %s",
735 pwd->pw_dir, strerror(errno));
741 if (consfd != 0 && (dup2(consfd, 1) < 0 || dup2(consfd, 2) < 0)) {
742 jail_warnx(j, "exec.consolelog: %s", strerror(errno));
746 execvp(argv[0], __DECONST(char *const*, argv));
747 jail_warnx(j, "exec %s: %s", argv[0], strerror(errno));
752 * Add a process to the hash, tied to a jail.
755 add_proc(struct cfjail *j, pid_t pid)
761 if (!kq && (kq = kqueue()) < 0)
763 EV_SET(&ke, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
764 if (kevent(kq, &ke, 1, NULL, 0, NULL) < 0) {
769 ph = emalloc(sizeof(struct phash));
772 LIST_INSERT_HEAD(&phash[pid % PHASH_SIZE], ph, le);
774 j->flags |= JF_SLEEPQ;
775 if (j->timeout.tv_sec == 0)
776 requeue(j, &sleeping);
778 /* File the jail in the sleep queue according to its timeout. */
779 TAILQ_REMOVE(j->queue, j, tq);
780 TAILQ_FOREACH(tj, &sleeping, tq) {
781 if (!tj->timeout.tv_sec ||
782 j->timeout.tv_sec < tj->timeout.tv_sec ||
783 (j->timeout.tv_sec == tj->timeout.tv_sec &&
784 j->timeout.tv_nsec <= tj->timeout.tv_nsec)) {
785 TAILQ_INSERT_BEFORE(tj, j, tq);
790 TAILQ_INSERT_TAIL(&sleeping, j, tq);
791 j->queue = &sleeping;
797 * Remove any processes from the hash that correspond to a jail.
800 clear_procs(struct cfjail *j)
803 struct phash *ph, *tph;
807 for (i = 0; i < PHASH_SIZE; i++)
808 LIST_FOREACH_SAFE(ph, &phash[i], le, tph)
810 EV_SET(&ke, ph->pid, EVFILT_PROC, EV_DELETE,
812 (void)kevent(kq, &ke, 1, NULL, 0, NULL);
819 * Find the jail that corresponds to an exited process.
821 static struct cfjail *
827 LIST_FOREACH(ph, &phash[pid % PHASH_SIZE], le)
828 if (ph->pid == pid) {
832 return --j->nprocs ? NULL : j;
838 * Send SIGTERM to all processes in a jail and wait for them to die.
841 term_procs(struct cfjail *j)
843 struct kinfo_proc *ki;
844 int i, noted, pcnt, timeout;
848 if (!int_param(j->intparams[IP_STOP_TIMEOUT], &timeout))
849 timeout = DEFAULT_STOP_TIMEOUT;
850 else if (timeout == 0)
854 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
859 ki = kvm_getprocs(kd, KERN_PROC_PROC, 0, &pcnt);
863 for (i = 0; i < pcnt; i++)
864 if (ki[i].ki_jid == j->jid &&
865 kill(ki[i].ki_pid, SIGTERM) == 0) {
866 (void)add_proc(j, ki[i].ki_pid);
870 jail_note(j, "sent SIGTERM to:");
872 printf(" %d", ki[i].ki_pid);
878 clock_gettime(CLOCK_REALTIME, &j->timeout);
879 j->timeout.tv_sec += timeout;
886 * Look up a user in the passwd and login.conf files.
889 get_user_info(struct cfjail *j, const char *username,
890 const struct passwd **pwdp, login_cap_t **lcapp)
892 const struct passwd *pwd;
895 *pwdp = pwd = username ? getpwnam(username) : getpwuid(getuid());
898 jail_warnx(j, "getpwnam%s%s: %s", username ? " " : "",
899 username ? username : "", strerror(errno));
901 jail_warnx(j, "%s: no such user", username);
903 jail_warnx(j, "unknown uid %d", getuid());
906 *lcapp = login_getpwclass(pwd);
907 if (*lcapp == NULL) {
908 jail_warnx(j, "getpwclass %s: %s", pwd->pw_name,
912 /* Set the groups while the group file is still available */
913 if (initgroups(pwd->pw_name, pwd->pw_gid) < 0) {
914 jail_warnx(j, "initgroups %s: %s", pwd->pw_name,
922 * Make sure a mount or consolelog path is a valid absolute pathname
926 check_path(struct cfjail *j, const char *pname, const char *path, int isfile,
927 const char *umount_type)
929 struct stat st, mpst;
932 const char *jailpath;
935 if (path[0] != '/') {
936 jail_warnx(j, "%s: %s: not an absolute pathname",
941 * Only check for symlinks in components below the jail's path,
942 * since that's where the security risk lies.
944 jailpath = string_param(j->intparams[KP_PATH]);
945 if (jailpath == NULL)
947 jplen = strlen(jailpath);
948 if (!strncmp(path, jailpath, jplen) && path[jplen] == '/') {
949 tpath = alloca(strlen(path) + 1);
951 for (p = tpath + jplen; p != NULL; ) {
952 p = strchr(p + 1, '/');
955 if (lstat(tpath, &st) < 0) {
956 if (errno == ENOENT && isfile && !p)
958 jail_warnx(j, "%s: %s: %s", pname, tpath,
962 if (S_ISLNK(st.st_mode)) {
963 jail_warnx(j, "%s: %s is a symbolic link",
971 if (umount_type != NULL) {
972 if (stat(path, &st) < 0 || statfs(path, &stfs) < 0) {
973 jail_warnx(j, "%s: %s: %s", pname, path,
977 if (stat(stfs.f_mntonname, &mpst) < 0) {
978 jail_warnx(j, "%s: %s: %s", pname, stfs.f_mntonname,
982 if (st.st_ino != mpst.st_ino) {
983 jail_warnx(j, "%s: %s: not a mount point",
987 if (strcmp(stfs.f_fstypename, umount_type)) {
988 jail_warnx(j, "%s: %s: not a %s mount",
989 pname, path, umount_type);