2 * A Process Isolator based on Linux Containers
4 * (c) 2012-2015 Martin Mares <mj@ucw.cz>
5 * (c) 2012-2014 Bernard Blackham <bernard@blackham.com.au>
8 /***********************************************************
9 ** This is not the master version of Isolate any longer. **
10 ** See https://github.com/ioi/isolate for its new home. **
11 ***********************************************************/
34 #include <sys/signal.h>
35 #include <sys/resource.h>
36 #include <sys/mount.h>
38 #include <sys/quota.h>
40 #include <sys/fsuid.h>
42 #define NONRET __attribute__((noreturn))
43 #define UNUSED __attribute__((unused))
44 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
46 static int timeout; /* milliseconds */
47 static int wall_timeout;
48 static int extra_timeout;
49 static int pass_environ;
51 static int memory_limit;
52 static int stack_limit;
53 static int block_quota;
54 static int inode_quota;
55 static int max_processes = 1;
56 static char *redir_stdin, *redir_stdout, *redir_stderr;
60 static int cg_memory_limit;
64 static char box_dir[1024];
69 static uid_t orig_uid;
70 static gid_t orig_gid;
72 static int partial_line;
73 static int cleanup_ownership;
75 static struct timeval start_time;
76 static int ticks_per_sec;
77 static int total_ms, wall_ms;
78 static volatile sig_atomic_t timer_tick;
80 static int error_pipes[2];
81 static int write_errors_to_fd;
82 static int read_errors_from_fd;
84 static void die(char *msg, ...) NONRET;
85 static void cg_stats(void);
86 static int get_wall_time_ms(void);
87 static int get_run_time_ms(struct rusage *rus);
89 static void chowntree(char *path, uid_t uid, gid_t gid);
93 static FILE *metafile;
96 meta_open(const char *name)
98 if (!strcmp(name, "-"))
103 if (setfsuid(getuid()) < 0)
104 die("Failed to switch FS UID: %m");
105 metafile = fopen(name, "w");
106 if (setfsuid(geteuid()) < 0)
107 die("Failed to switch FS UID back: %m");
109 die("Failed to open metafile '%s'",name);
115 if (metafile && metafile != stdout)
119 static void __attribute__((format(printf,1,2)))
120 meta_printf(const char *fmt, ...)
127 vfprintf(metafile, fmt, args);
132 final_stats(struct rusage *rus)
134 total_ms = get_run_time_ms(rus);
135 wall_ms = get_wall_time_ms();
137 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
138 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
139 meta_printf("max-rss:%ld\n", rus->ru_maxrss);
140 meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
141 meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
146 /*** Messages and exits ***/
153 kill(-box_pid, SIGKILL);
154 kill(box_pid, SIGKILL);
155 meta_printf("killed:1\n");
160 p = wait4(box_pid, &stat, 0, &rus);
161 while (p < 0 && errno == EINTR);
163 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
168 if (rc < 2 && cleanup_ownership)
169 chowntree("box", orig_uid, orig_gid);
183 /* Report an error of the sandbox itself */
184 static void NONRET __attribute__((format(printf,1,2)))
190 int n = vsnprintf(buf, sizeof(buf), msg, args);
192 if (write_errors_to_fd)
194 // We are inside the box, have to use error pipe for error reporting.
195 // We hope that the whole error message fits in PIPE_BUF bytes.
196 write(write_errors_to_fd, buf, n);
200 // Otherwise, we in the box keeper process, so we report errors normally
202 meta_printf("status:XX\nmessage:%s\n", buf);
208 /* Report an error of the program inside the sandbox */
209 static void NONRET __attribute__((format(printf,1,2)))
215 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
217 meta_printf("status:%c%c\n", msg[0], msg[1]);
221 vsnprintf(buf, sizeof(buf), msg, args);
222 meta_printf("message:%s\n", buf);
228 /* Write a message, but only if in verbose mode */
229 static void __attribute__((format(printf,1,2)))
236 int len = strlen(msg);
238 partial_line = (msg[len-1] != '\n');
239 vfprintf(stderr, msg, args);
245 /*** Utility functions ***/
250 void *p = malloc(size);
252 die("Out of memory");
259 char *p = strdup(str);
261 die("Out of memory");
265 static int dir_exists(char *path)
268 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
271 static int rmtree_helper(const char *fpath, const struct stat *sb,
272 int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
274 if (S_ISDIR(sb->st_mode))
276 if (rmdir(fpath) < 0)
277 die("Cannot rmdir %s: %m", fpath);
281 if (unlink(fpath) < 0)
282 die("Cannot unlink %s: %m", fpath);
290 nftw(path, rmtree_helper, 32, FTW_MOUNT | FTW_PHYS | FTW_DEPTH);
293 static uid_t chown_uid;
294 static gid_t chown_gid;
296 static int chowntree_helper(const char *fpath, const struct stat *sb UNUSED,
297 int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
299 if (lchown(fpath, chown_uid, chown_gid) < 0)
300 die("Cannot chown %s: %m", fpath);
306 chowntree(char *path, uid_t uid, gid_t gid)
310 nftw(path, chowntree_helper, 32, FTW_MOUNT | FTW_PHYS);
313 /*** Environment rules ***/
316 char *var; // Variable to match
317 char *val; // ""=clear, NULL=inherit
319 struct env_rule *next;
322 static struct env_rule *first_env_rule;
323 static struct env_rule **last_env_rule = &first_env_rule;
325 static struct env_rule default_env_rules[] = {
326 { "LIBC_FATAL_STDERR_", "1" }
330 set_env_action(char *a0)
332 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
333 char *a = (char *)(r+1);
336 char *sep = strchr(a, '=');
348 last_env_rule = &r->next;
354 match_env_var(char *env_entry, struct env_rule *r)
356 if (strncmp(env_entry, r->var, r->var_len))
358 return (env_entry[r->var_len] == '=');
362 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
364 // First remove the variable if already set
366 while (pos < *env_sizep && !match_env_var(env[pos], r))
368 if (pos < *env_sizep)
371 env[pos] = env[*env_sizep];
372 env[*env_sizep] = NULL;
375 // What is the new value?
381 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
382 sprintf(new, "%s=%s", r->var, r->val);
387 while (environ[pos] && !match_env_var(environ[pos], r))
389 if (!(new = environ[pos]))
393 // Add it at the end of the array
394 env[(*env_sizep)++] = new;
395 env[*env_sizep] = NULL;
399 setup_environment(void)
401 // Link built-in rules with user rules
402 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
404 default_env_rules[i].next = first_env_rule;
405 first_env_rule = &default_env_rules[i];
408 // Scan the original environment
409 char **orig_env = environ;
411 while (orig_env[orig_size])
414 // For each rule, reserve one more slot and calculate length
416 for (struct env_rule *r = first_env_rule; r; r=r->next)
419 r->var_len = strlen(r->var);
422 // Create a new environment
423 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
427 memcpy(env, environ, orig_size * sizeof(char *));
434 // Apply the rules one by one
435 for (struct env_rule *r = first_env_rule; r; r=r->next)
436 apply_env_rule(env, &size, r);
438 // Return the new env and pass some gossip
441 fprintf(stderr, "Passing environment:\n");
442 for (int i=0; env[i]; i++)
443 fprintf(stderr, "\t%s\n", env[i]);
448 /*** Directory rules ***/
451 char *inside; // A relative path
452 char *outside; // This can be an absolute path or a relative path starting with "./"
453 unsigned int flags; // DIR_FLAG_xxx
454 struct dir_rule *next;
457 enum dir_rule_flags {
465 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
467 static struct dir_rule *first_dir_rule;
468 static struct dir_rule **last_dir_rule = &first_dir_rule;
470 static int add_dir_rule(char *in, char *out, unsigned int flags)
472 // Make sure that "in" is relative
479 if (flags & DIR_FLAG_FS)
481 if (!out || out[0] == '/')
486 if (out && out[0] != '/' && strncmp(out, "./", 2))
490 // Override an existing rule
492 for (r = first_dir_rule; r; r = r->next)
493 if (!strcmp(r->inside, in))
499 r = xmalloc(sizeof(*r));
502 last_dir_rule = &r->next;
510 static unsigned int parse_dir_option(char *opt)
512 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
513 if (!strcmp(opt, dir_flag_names[i]))
515 die("Unknown directory option %s", opt);
518 static int set_dir_action(char *arg)
522 char *colon = strchr(arg, ':');
523 unsigned int flags = 0;
527 char *next = strchr(colon, ':');
530 flags |= parse_dir_option(colon);
534 char *eq = strchr(arg, '=');
538 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
542 char *out = xmalloc(1 + strlen(arg) + 1);
543 sprintf(out, "/%s", arg);
544 return add_dir_rule(arg, out, flags);
548 static void init_dir_rules(void)
550 set_dir_action("box=./box:rw");
551 set_dir_action("bin");
552 set_dir_action("dev:dev");
553 set_dir_action("lib");
554 set_dir_action("lib64:maybe");
555 set_dir_action("proc=proc:fs");
556 set_dir_action("usr");
559 static void make_dir(char *path)
561 char *sep = (path[0] == '/' ? path+1 : path);
565 sep = strchr(sep, '/');
569 if (!dir_exists(path) && mkdir(path, 0777) < 0)
570 die("Cannot create directory %s: %m\n", path);
578 static void apply_dir_rules(void)
580 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
582 char *in = r->inside;
583 char *out = r->outside;
586 msg("Not binding anything on %s\n", r->inside);
590 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
592 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
597 snprintf(root_in, sizeof(root_in), "root/%s", in);
600 unsigned long mount_flags = 0;
601 if (!(r->flags & DIR_FLAG_RW))
602 mount_flags |= MS_RDONLY;
603 if (r->flags & DIR_FLAG_NOEXEC)
604 mount_flags |= MS_NOEXEC;
605 if (!(r->flags & DIR_FLAG_DEV))
606 mount_flags |= MS_NODEV;
608 if (r->flags & DIR_FLAG_FS)
610 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
611 if (mount("none", root_in, out, mount_flags, "") < 0)
612 die("Cannot mount %s on %s: %m", out, in);
616 mount_flags |= MS_BIND | MS_NOSUID;
617 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
618 // Most mount flags need remount to work
619 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
620 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
621 die("Cannot mount %s on %s: %m", out, in);
626 /*** Control groups ***/
628 struct cg_controller_desc {
640 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
641 [CG_MEMORY] = { "memory", 0 },
642 [CG_CPUACCT] = { "cpuacct", 0 },
643 [CG_CPUSET] = { "cpuset", 1 },
644 [CG_NUM_CONTROLLERS] = { NULL, 0 },
647 #define FOREACH_CG_CONTROLLER(_controller) \
648 for (cg_controller (_controller) = 0; \
649 (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
651 static const char *cg_controller_name(cg_controller c)
653 return cg_controllers[c].name;
656 static int cg_controller_optional(cg_controller c)
658 return cg_controllers[c].optional;
661 static char cg_name[256];
663 #define CG_BUFSIZE 1024
666 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
668 const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
669 snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
673 cg_read(cg_controller controller, const char *attr, char *buf)
683 cg_makepath(path, sizeof(path), controller, attr);
685 int fd = open(path, O_RDONLY);
690 die("Cannot read %s: %m", path);
693 int n = read(fd, buf, CG_BUFSIZE);
698 die("Cannot read %s: %m", path);
700 if (n >= CG_BUFSIZE - 1)
701 die("Attribute %s too long", path);
702 if (n > 0 && buf[n-1] == '\n')
707 msg("CG: Read %s = %s\n", attr, buf);
713 static void __attribute__((format(printf,3,4)))
714 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
726 char buf[CG_BUFSIZE];
727 int n = vsnprintf(buf, sizeof(buf), fmt, args);
729 die("cg_write: Value for attribute %s is too long", attr);
732 msg("CG: Write %s = %s", attr, buf);
735 cg_makepath(path, sizeof(path), controller, attr);
737 int fd = open(path, O_WRONLY | O_TRUNC);
743 die("Cannot write %s: %m", path);
746 int written = write(fd, buf, n);
752 die("Cannot set %s to %s: %m", path, buf);
755 die("Short write to %s (%d out of %d bytes)", path, written, n);
767 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
768 if (!dir_exists(cg_root))
769 die("Control group filesystem at %s not mounted", cg_root);
771 snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
772 msg("Using control group %s\n", cg_name);
782 char buf[CG_BUFSIZE];
785 FOREACH_CG_CONTROLLER(controller)
787 cg_makepath(path, sizeof(path), controller, "");
788 if (stat(path, &st) >= 0 || errno != ENOENT)
790 msg("Control group %s already exists, trying to empty it.\n", path);
792 die("Failed to reset control group %s: %m", path);
795 if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
796 die("Failed to create control group %s: %m", path);
799 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
800 if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
801 cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
802 if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
803 cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
812 msg("Entering control group %s\n", cg_name);
814 FOREACH_CG_CONTROLLER(controller)
816 if (cg_controller_optional(controller))
817 cg_write(controller, "?tasks", "%d\n", (int) getpid());
819 cg_write(controller, "tasks", "%d\n", (int) getpid());
824 cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
825 cg_write(CG_MEMORY, "?memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
829 cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
833 cg_get_run_time_ms(void)
838 char buf[CG_BUFSIZE];
839 cg_read(CG_CPUACCT, "cpuacct.usage", buf);
840 unsigned long long ns = atoll(buf);
850 char buf[CG_BUFSIZE];
852 // Memory usage statistics
853 unsigned long long mem=0, memsw=0;
854 if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
856 if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
863 meta_printf("cg-mem:%lld\n", mem >> 10);
869 char buf[CG_BUFSIZE];
874 FOREACH_CG_CONTROLLER(controller)
876 if (cg_controller_optional(controller))
878 if (!cg_read(controller, "?tasks", buf))
882 cg_read(controller, "tasks", buf);
885 die("Some tasks left in controller %s of cgroup %s, failed to remove it",
886 cg_controller_name(controller), cg_name);
889 cg_makepath(path, sizeof(path), controller, "");
892 die("Cannot remove control group %s: %m", path);
896 /*** Disk quotas ***/
899 path_begins_with(char *path, char *with)
902 if (*path++ != *with++)
904 return (!*with || *with == '/');
908 find_device(char *path)
910 FILE *f = setmntent("/proc/mounts", "r");
912 die("Cannot open /proc/mounts: %m");
916 char *best_dev = NULL;
917 while (me = getmntent(f))
919 if (!path_begins_with(me->mnt_fsname, "/dev"))
921 if (path_begins_with(path, me->mnt_dir))
923 int len = strlen(me->mnt_dir);
928 best_dev = xstrdup(me->mnt_fsname);
943 if (!getcwd(cwd, sizeof(cwd)))
946 char *dev = find_device(cwd);
948 die("Cannot identify filesystem which contains %s", cwd);
949 msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
952 struct stat dev_st, cwd_st;
953 if (stat(dev, &dev_st) < 0)
954 die("Cannot identify block device %s: %m", dev);
955 if (!S_ISBLK(dev_st.st_mode))
956 die("Expected that %s is a block device", dev);
957 if (stat(".", &cwd_st) < 0)
958 die("Cannot stat cwd: %m");
959 if (cwd_st.st_dev != dev_st.st_rdev)
960 die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
963 .dqb_bhardlimit = block_quota,
964 .dqb_bsoftlimit = block_quota,
965 .dqb_ihardlimit = inode_quota,
966 .dqb_isoftlimit = inode_quota,
967 .dqb_valid = QIF_LIMITS,
969 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
970 die("Cannot set disk quota: %m");
971 msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
976 /*** The keeper process ***/
979 signal_alarm(int unused UNUSED)
981 /* Time limit checks are synchronous, so we only schedule them there. */
987 signal_int(int unused UNUSED)
989 /* Interrupts are fatal, so no synchronization requirements. */
990 meta_printf("exitsig:%d\n", SIGINT);
991 err("SG: Interrupted");
994 #define PROC_BUF_SIZE 4096
996 read_proc_file(char *buf, char *name, int *fdp)
1002 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
1003 *fdp = open(buf, O_RDONLY);
1005 die("open(%s): %m", buf);
1007 lseek(*fdp, 0, SEEK_SET);
1008 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
1009 die("read on /proc/$pid/%s: %m", name);
1010 if (c >= PROC_BUF_SIZE-1)
1011 die("/proc/$pid/%s too long", name);
1016 get_wall_time_ms(void)
1018 struct timeval now, wall;
1019 gettimeofday(&now, NULL);
1020 timersub(&now, &start_time, &wall);
1021 return wall.tv_sec*1000 + wall.tv_usec/1000;
1025 get_run_time_ms(struct rusage *rus)
1028 return cg_get_run_time_ms();
1032 struct timeval total;
1033 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
1034 return total.tv_sec*1000 + total.tv_usec/1000;
1037 char buf[PROC_BUF_SIZE], *x;
1039 static int proc_stat_fd;
1041 read_proc_file(buf, "stat", &proc_stat_fd);
1043 while (*x && *x != ' ')
1048 die("proc stat syntax error 1");
1049 while (*x && (*x != ')' || x[1] != ' '))
1051 while (*x == ')' || *x == ' ')
1053 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1054 die("proc stat syntax error 2");
1056 return (utime + stime) * 1000 / ticks_per_sec;
1064 int wall_ms = get_wall_time_ms();
1065 if (wall_ms > wall_timeout)
1066 err("TO: Time limit exceeded (wall clock)");
1068 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1072 int ms = get_run_time_ms(NULL);
1074 fprintf(stderr, "[time check: %d msec]\n", ms);
1075 if (ms > timeout && ms > extra_timeout)
1076 err("TO: Time limit exceeded");
1083 read_errors_from_fd = error_pipes[0];
1084 close(error_pipes[1]);
1086 struct sigaction sa;
1087 bzero(&sa, sizeof(sa));
1088 sa.sa_handler = signal_int;
1089 sigaction(SIGINT, &sa, NULL);
1091 gettimeofday(&start_time, NULL);
1092 ticks_per_sec = sysconf(_SC_CLK_TCK);
1093 if (ticks_per_sec <= 0)
1094 die("Invalid ticks_per_sec!");
1096 if (timeout || wall_timeout)
1098 sa.sa_handler = signal_alarm;
1099 sigaction(SIGALRM, &sa, NULL);
1113 p = wait4(box_pid, &stat, 0, &rus);
1121 die("wait4: unknown pid %d exited!", p);
1124 // Check error pipe if there is an internal error passed from inside the box
1126 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1133 if (WIFEXITED(stat))
1136 if (WEXITSTATUS(stat))
1138 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1139 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1141 if (timeout && total_ms > timeout)
1142 err("TO: Time limit exceeded");
1143 if (wall_timeout && wall_ms > wall_timeout)
1144 err("TO: Time limit exceeded (wall clock)");
1146 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1147 total_ms/1000, total_ms%1000,
1148 wall_ms/1000, wall_ms%1000);
1151 else if (WIFSIGNALED(stat))
1153 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1155 err("SG: Caught fatal signal %d", WTERMSIG(stat));
1157 else if (WIFSTOPPED(stat))
1159 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1161 err("SG: Stopped by signal %d", WSTOPSIG(stat));
1164 die("wait4: unknown status %x, giving up!", stat);
1168 /*** The process running inside the box ***/
1173 if (mkdir("root", 0750) < 0 && errno != EEXIST)
1174 die("mkdir('root'): %m");
1176 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1177 die("Cannot mount root ramdisk: %m");
1181 if (chroot("root") < 0)
1182 die("Chroot failed: %m");
1184 if (chdir("root/box") < 0)
1185 die("Cannot change current directory: %m");
1189 setup_credentials(void)
1191 if (setresgid(box_gid, box_gid, box_gid) < 0)
1192 die("setresgid: %m");
1193 if (setgroups(0, NULL) < 0)
1194 die("setgroups: %m");
1195 if (setresuid(box_uid, box_uid, box_uid) < 0)
1196 die("setresuid: %m");
1206 if (open(redir_stdin, O_RDONLY) != 0)
1207 die("open(\"%s\"): %m", redir_stdin);
1212 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1213 die("open(\"%s\"): %m", redir_stdout);
1218 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1219 die("open(\"%s\"): %m", redir_stderr);
1226 setup_rlim(const char *res_name, int res, rlim_t limit)
1228 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1229 if (setrlimit(res, &rl) < 0)
1230 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1236 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1239 RLIM(AS, (rlim_t)memory_limit * 1024);
1241 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1246 RLIM(NPROC, max_processes);
1252 box_inside(void *arg)
1255 write_errors_to_fd = error_pipes[1];
1256 close(error_pipes[0]);
1261 setup_credentials();
1264 char **env = setup_environment();
1266 if (set_cwd && chdir(set_cwd))
1269 execve(args[0], args, env);
1270 die("execve(\"%s\"): %m", args[0]);
1276 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1277 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1278 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1279 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1281 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1283 if (chdir(box_dir) < 0)
1284 die("chdir(%s): %m", box_dir);
1292 msg("Preparing sandbox directory\n");
1294 if (mkdir("box", 0700) < 0)
1295 die("Cannot create box: %m");
1296 if (chown("box", orig_uid, orig_gid) < 0)
1297 die("Cannot chown box: %m");
1308 if (!dir_exists("box"))
1309 die("Box directory not found, there isn't anything to clean up");
1311 msg("Deleting sandbox directory\n");
1319 if (!dir_exists("box"))
1320 die("Box directory not found, did you run `isolate --init'?");
1322 chowntree("box", box_uid, box_gid);
1323 cleanup_ownership = 1;
1325 if (pipe(error_pipes) < 0)
1327 for (int i=0; i<2; i++)
1328 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1329 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1330 die("fcntl on pipe: %m");
1333 box_inside, // Function to execute as the body of the new process
1334 argv, // Pass our stack
1335 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1336 argv); // Pass the arguments
1340 die("clone returned 0");
1347 printf("Process isolator 1.0\n");
1348 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1349 printf("\nCompile-time configuration:\n");
1350 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1351 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1352 CONFIG_ISOLATE_FIRST_UID,
1353 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1354 CONFIG_ISOLATE_FIRST_GID,
1355 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1360 static void __attribute__((format(printf,1,2)))
1361 usage(const char *msg, ...)
1366 va_start(args, msg);
1367 vfprintf(stderr, msg, args);
1371 Usage: isolate [<options>] <command>\n\
1374 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1375 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1376 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1377 --cg-timing\t\tTime limits affects total run time of the control group\n\
1378 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1379 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1380 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1381 --dir=...:<opt>\tSpecify options for a rule:\n\
1382 \t\t\t\tdev\tAllow access to special files\n\
1383 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1384 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1385 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1386 \t\t\t\trw\tAllow read-write access\n\
1387 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1388 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1389 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1390 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1391 -e, --full-env\t\tInherit full environment of the parent process\n\
1392 -m, --mem=<size>\tLimit address space to <size> KB\n\
1393 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1394 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1395 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1396 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1397 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1398 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1399 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1400 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1401 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1402 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1405 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1406 --run -- <cmd> ...\tRun given command within sandbox\n\
1407 --cleanup\t\tClean up sandbox\n\
1408 --version\t\tDisplay program version and configuration\n\
1423 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1425 static const struct option long_opts[] = {
1426 { "box-id", 1, NULL, 'b' },
1427 { "chdir", 1, NULL, 'c' },
1428 { "cg", 0, NULL, OPT_CG },
1429 { "cg-mem", 1, NULL, OPT_CG_MEM },
1430 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1431 { "cleanup", 0, NULL, OPT_CLEANUP },
1432 { "dir", 1, NULL, 'd' },
1433 { "env", 1, NULL, 'E' },
1434 { "extra-time", 1, NULL, 'x' },
1435 { "full-env", 0, NULL, 'e' },
1436 { "init", 0, NULL, OPT_INIT },
1437 { "mem", 1, NULL, 'm' },
1438 { "meta", 1, NULL, 'M' },
1439 { "processes", 2, NULL, 'p' },
1440 { "quota", 1, NULL, 'q' },
1441 { "run", 0, NULL, OPT_RUN },
1442 { "stack", 1, NULL, 'k' },
1443 { "stderr", 1, NULL, 'r' },
1444 { "stdin", 1, NULL, 'i' },
1445 { "stdout", 1, NULL, 'o' },
1446 { "time", 1, NULL, 't' },
1447 { "verbose", 0, NULL, 'v' },
1448 { "version", 0, NULL, OPT_VERSION },
1449 { "wall-time", 1, NULL, 'w' },
1450 { NULL, 0, NULL, 0 }
1454 main(int argc, char **argv)
1458 enum opt_code mode = 0;
1462 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1466 box_id = atoi(optarg);
1475 if (!set_dir_action(optarg))
1476 usage("Invalid directory specified: %s\n", optarg);
1482 if (!set_env_action(optarg))
1483 usage("Invalid environment specified: %s\n", optarg);
1486 stack_limit = atoi(optarg);
1489 redir_stdin = optarg;
1492 memory_limit = atoi(optarg);
1498 redir_stdout = optarg;
1502 max_processes = atoi(optarg);
1507 sep = strchr(optarg, ',');
1509 usage("Invalid quota specified: %s\n", optarg);
1510 block_quota = atoi(optarg);
1511 inode_quota = atoi(sep+1);
1514 redir_stderr = optarg;
1517 timeout = 1000*atof(optarg);
1523 wall_timeout = 1000*atof(optarg);
1526 extra_timeout = 1000*atof(optarg);
1532 if (!mode || (int) mode == c)
1535 usage("Only one command is allowed.\n");
1538 cg_memory_limit = atoi(optarg);
1548 usage("Please specify an isolate command (e.g. --init, --run).\n");
1549 if (mode == OPT_VERSION)
1556 die("Must be started as root");
1557 orig_uid = getuid();
1558 orig_gid = getgid();
1568 usage("--init mode takes no parameters\n");
1573 usage("--run mode requires a command to run\n");
1578 usage("--cleanup mode takes no parameters\n");
1582 die("Internal error: mode mismatch");