2 * A Process Isolator based on Linux Containers
4 * (c) 2012-2013 Martin Mares <mj@ucw.cz>
5 * (c) 2012-2013 Bernard Blackham <bernard@blackham.com.au>
28 #include <sys/signal.h>
29 #include <sys/resource.h>
30 #include <sys/mount.h>
32 #include <sys/quota.h>
35 #define NONRET __attribute__((noreturn))
36 #define UNUSED __attribute__((unused))
37 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
39 static int timeout; /* milliseconds */
40 static int wall_timeout;
41 static int extra_timeout;
42 static int pass_environ;
44 static int memory_limit;
45 static int stack_limit;
46 static int block_quota;
47 static int inode_quota;
48 static int max_processes = 1;
49 static char *redir_stdin, *redir_stdout, *redir_stderr;
53 static int cg_memory_limit;
57 static char box_dir[1024];
62 static uid_t orig_uid;
63 static gid_t orig_gid;
65 static int partial_line;
66 static char cleanup_cmd[256];
68 static struct timeval start_time;
69 static int ticks_per_sec;
70 static int total_ms, wall_ms;
71 static volatile sig_atomic_t timer_tick;
73 static int error_pipes[2];
74 static int write_errors_to_fd;
75 static int read_errors_from_fd;
77 static void die(char *msg, ...) NONRET;
78 static void cg_stats(void);
79 static int get_wall_time_ms(void);
80 static int get_run_time_ms(struct rusage *rus);
84 static FILE *metafile;
87 meta_open(const char *name)
89 if (!strcmp(name, "-"))
94 metafile = fopen(name, "w");
96 die("Failed to open metafile '%s'",name);
102 if (metafile && metafile != stdout)
106 static void __attribute__((format(printf,1,2)))
107 meta_printf(const char *fmt, ...)
114 vfprintf(metafile, fmt, args);
119 final_stats(struct rusage *rus)
121 total_ms = get_run_time_ms(rus);
122 wall_ms = get_wall_time_ms();
124 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
125 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
126 meta_printf("max-rss:%ld\n", rus->ru_maxrss);
127 meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
128 meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
133 /*** Messages and exits ***/
136 xsystem(const char *cmd)
138 int ret = system(cmd);
140 die("system(\"%s\"): %m", cmd);
141 if (!WIFEXITED(ret) || WEXITSTATUS(ret))
142 die("system(\"%s\"): Exited with status %d", cmd, ret);
150 kill(-box_pid, SIGKILL);
151 kill(box_pid, SIGKILL);
152 meta_printf("killed:1\n");
157 p = wait4(box_pid, &stat, 0, &rus);
158 while (p < 0 && errno == EINTR);
160 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
165 if (rc < 2 && cleanup_cmd[0])
166 xsystem(cleanup_cmd);
180 /* Report an error of the sandbox itself */
181 static void NONRET __attribute__((format(printf,1,2)))
187 int n = vsnprintf(buf, sizeof(buf), msg, args);
189 if (write_errors_to_fd)
191 // We are inside the box, have to use error pipe for error reporting.
192 // We hope that the whole error message fits in PIPE_BUF bytes.
193 write(write_errors_to_fd, buf, n);
197 // Otherwise, we in the box keeper process, so we report errors normally
199 meta_printf("status:XX\nmessage:%s\n", buf);
205 /* Report an error of the program inside the sandbox */
206 static void NONRET __attribute__((format(printf,1,2)))
212 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
214 meta_printf("status:%c%c\n", msg[0], msg[1]);
218 vsnprintf(buf, sizeof(buf), msg, args);
219 meta_printf("message:%s\n", buf);
225 /* Write a message, but only if in verbose mode */
226 static void __attribute__((format(printf,1,2)))
233 int len = strlen(msg);
235 partial_line = (msg[len-1] != '\n');
236 vfprintf(stderr, msg, args);
242 /*** Utility functions ***/
247 void *p = malloc(size);
249 die("Out of memory");
256 char *p = strdup(str);
258 die("Out of memory");
262 static int dir_exists(char *path)
265 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
268 /*** Environment rules ***/
271 char *var; // Variable to match
272 char *val; // ""=clear, NULL=inherit
274 struct env_rule *next;
277 static struct env_rule *first_env_rule;
278 static struct env_rule **last_env_rule = &first_env_rule;
280 static struct env_rule default_env_rules[] = {
281 { "LIBC_FATAL_STDERR_", "1" }
285 set_env_action(char *a0)
287 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
288 char *a = (char *)(r+1);
291 char *sep = strchr(a, '=');
303 last_env_rule = &r->next;
309 match_env_var(char *env_entry, struct env_rule *r)
311 if (strncmp(env_entry, r->var, r->var_len))
313 return (env_entry[r->var_len] == '=');
317 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
319 // First remove the variable if already set
321 while (pos < *env_sizep && !match_env_var(env[pos], r))
323 if (pos < *env_sizep)
326 env[pos] = env[*env_sizep];
327 env[*env_sizep] = NULL;
330 // What is the new value?
336 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
337 sprintf(new, "%s=%s", r->var, r->val);
342 while (environ[pos] && !match_env_var(environ[pos], r))
344 if (!(new = environ[pos]))
348 // Add it at the end of the array
349 env[(*env_sizep)++] = new;
350 env[*env_sizep] = NULL;
354 setup_environment(void)
356 // Link built-in rules with user rules
357 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
359 default_env_rules[i].next = first_env_rule;
360 first_env_rule = &default_env_rules[i];
363 // Scan the original environment
364 char **orig_env = environ;
366 while (orig_env[orig_size])
369 // For each rule, reserve one more slot and calculate length
371 for (struct env_rule *r = first_env_rule; r; r=r->next)
374 r->var_len = strlen(r->var);
377 // Create a new environment
378 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
382 memcpy(env, environ, orig_size * sizeof(char *));
389 // Apply the rules one by one
390 for (struct env_rule *r = first_env_rule; r; r=r->next)
391 apply_env_rule(env, &size, r);
393 // Return the new env and pass some gossip
396 fprintf(stderr, "Passing environment:\n");
397 for (int i=0; env[i]; i++)
398 fprintf(stderr, "\t%s\n", env[i]);
403 /*** Directory rules ***/
406 char *inside; // A relative path
407 char *outside; // This can be an absolute path or a relative path starting with "./"
408 unsigned int flags; // DIR_FLAG_xxx
409 struct dir_rule *next;
412 enum dir_rule_flags {
420 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
422 static struct dir_rule *first_dir_rule;
423 static struct dir_rule **last_dir_rule = &first_dir_rule;
425 static int add_dir_rule(char *in, char *out, unsigned int flags)
427 // Make sure that "in" is relative
434 if (flags & DIR_FLAG_FS)
436 if (!out || out[0] == '/')
441 if (out && out[0] != '/' && strncmp(out, "./", 2))
445 // Override an existing rule
447 for (r = first_dir_rule; r; r = r->next)
448 if (!strcmp(r->inside, in))
454 r = xmalloc(sizeof(*r));
457 last_dir_rule = &r->next;
465 static unsigned int parse_dir_option(char *opt)
467 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
468 if (!strcmp(opt, dir_flag_names[i]))
470 die("Unknown directory option %s", opt);
473 static int set_dir_action(char *arg)
477 char *colon = strchr(arg, ':');
478 unsigned int flags = 0;
482 char *next = strchr(colon, ':');
485 flags |= parse_dir_option(colon);
489 char *eq = strchr(arg, '=');
493 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
497 char *out = xmalloc(1 + strlen(arg) + 1);
498 sprintf(out, "/%s", arg);
499 return add_dir_rule(arg, out, flags);
503 static void init_dir_rules(void)
505 set_dir_action("box=./box:rw");
506 set_dir_action("bin");
507 set_dir_action("dev:dev");
508 set_dir_action("lib");
509 set_dir_action("lib64:maybe");
510 set_dir_action("proc=proc:fs");
511 set_dir_action("usr");
514 static void make_dir(char *path)
516 char *sep = (path[0] == '/' ? path+1 : path);
520 sep = strchr(sep, '/');
524 if (!dir_exists(path) && mkdir(path, 0777) < 0)
525 die("Cannot create directory %s: %m\n", path);
533 static void apply_dir_rules(void)
535 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
537 char *in = r->inside;
538 char *out = r->outside;
541 msg("Not binding anything on %s\n", r->inside);
545 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
547 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
552 snprintf(root_in, sizeof(root_in), "root/%s", in);
555 unsigned long mount_flags = 0;
556 if (!(r->flags & DIR_FLAG_RW))
557 mount_flags |= MS_RDONLY;
558 if (r->flags & DIR_FLAG_NOEXEC)
559 mount_flags |= MS_NOEXEC;
560 if (!(r->flags & DIR_FLAG_DEV))
561 mount_flags |= MS_NODEV;
563 if (r->flags & DIR_FLAG_FS)
565 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
566 if (mount("none", root_in, out, mount_flags, "") < 0)
567 die("Cannot mount %s on %s: %m", out, in);
571 mount_flags |= MS_BIND | MS_NOSUID;
572 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
573 // Most mount flags need remount to work
574 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
575 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
576 die("Cannot mount %s on %s: %m", out, in);
581 /*** Control groups ***/
583 struct cg_controller_desc {
595 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
596 [CG_MEMORY] = { "memory", 0 },
597 [CG_CPUACCT] = { "cpuacct", 0 },
598 [CG_CPUSET] = { "cpuset", 1 },
599 [CG_NUM_CONTROLLERS] = { NULL, 0 },
602 #define FOREACH_CG_CONTROLLER(_controller) \
603 for (cg_controller (_controller) = 0; \
604 (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
606 static const char *cg_controller_name(cg_controller c)
608 return cg_controllers[c].name;
611 static const int cg_controller_optional(cg_controller c)
613 return cg_controllers[c].optional;
616 static char cg_name[256];
618 #define CG_BUFSIZE 1024
621 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
623 const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
624 snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
628 cg_read(cg_controller controller, const char *attr, char *buf)
638 cg_makepath(path, sizeof(path), controller, attr);
640 int fd = open(path, O_RDONLY);
645 die("Cannot read %s: %m", path);
648 int n = read(fd, buf, CG_BUFSIZE);
650 die("Cannot read %s: %m", path);
651 if (n >= CG_BUFSIZE - 1)
652 die("Attribute %s too long", path);
653 if (n > 0 && buf[n-1] == '\n')
658 msg("CG: Read %s = %s\n", attr, buf);
664 static void __attribute__((format(printf,3,4)))
665 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
677 char buf[CG_BUFSIZE];
678 int n = vsnprintf(buf, sizeof(buf), fmt, args);
680 die("cg_write: Value for attribute %s is too long", attr);
683 msg("CG: Write %s = %s", attr, buf);
686 cg_makepath(path, sizeof(path), controller, attr);
688 int fd = open(path, O_WRONLY | O_TRUNC);
694 die("Cannot write %s: %m", path);
697 int written = write(fd, buf, n);
703 die("Cannot set %s to %s: %m", path, buf);
706 die("Short write to %s (%d out of %d bytes)", path, written, n);
718 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
719 if (!dir_exists(cg_root))
720 die("Control group filesystem at %s not mounted", cg_root);
722 snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
723 msg("Using control group %s\n", cg_name);
733 char buf[CG_BUFSIZE];
736 FOREACH_CG_CONTROLLER(controller)
738 cg_makepath(path, sizeof(path), controller, "");
739 if (stat(path, &st) >= 0 || errno != ENOENT)
741 msg("Control group %s already exists, trying to empty it.\n", path);
743 die("Failed to reset control group %s: %m", path);
746 if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
747 die("Failed to create control group %s: %m", path);
750 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
751 if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
752 cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
753 if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
754 cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
763 msg("Entering control group %s\n", cg_name);
765 FOREACH_CG_CONTROLLER(controller)
767 if (cg_controller_optional(controller))
768 cg_write(controller, "?tasks", "%d\n", (int) getpid());
770 cg_write(controller, "tasks", "%d\n", (int) getpid());
775 cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
776 cg_write(CG_MEMORY, "memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
780 cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
784 cg_get_run_time_ms(void)
789 char buf[CG_BUFSIZE];
790 cg_read(CG_CPUACCT, "cpuacct.usage", buf);
791 unsigned long long ns = atoll(buf);
801 char buf[CG_BUFSIZE];
803 // Memory usage statistics
804 unsigned long long mem=0, memsw=0;
805 if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
807 if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
814 meta_printf("cg-mem:%lld\n", mem >> 10);
820 char buf[CG_BUFSIZE];
825 FOREACH_CG_CONTROLLER(controller)
827 if (cg_controller_optional(controller)) {
828 if (!cg_read(controller, "?tasks", buf))
831 cg_read(controller, "tasks", buf);
834 die("Some tasks left in controller %s of cgroup %s, failed to remove it",
835 cg_controller_name(controller), cg_name);
838 cg_makepath(path, sizeof(path), controller, "");
841 die("Cannot remove control group %s: %m", path);
845 /*** Disk quotas ***/
848 path_begins_with(char *path, char *with)
851 if (*path++ != *with++)
853 return (!*with || *with == '/');
857 find_device(char *path)
859 FILE *f = setmntent("/proc/mounts", "r");
861 die("Cannot open /proc/mounts: %m");
865 char *best_dev = NULL;
866 while (me = getmntent(f))
868 if (!path_begins_with(me->mnt_fsname, "/dev"))
870 if (path_begins_with(path, me->mnt_dir))
872 int len = strlen(me->mnt_dir);
877 best_dev = xstrdup(me->mnt_fsname);
892 if (!getcwd(cwd, sizeof(cwd)))
895 char *dev = find_device(cwd);
897 die("Cannot identify filesystem which contains %s", cwd);
898 msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
901 struct stat dev_st, cwd_st;
902 if (stat(dev, &dev_st) < 0)
903 die("Cannot identify block device %s: %m", dev);
904 if (!S_ISBLK(dev_st.st_mode))
905 die("Expected that %s is a block device", dev);
906 if (stat(".", &cwd_st) < 0)
907 die("Cannot stat cwd: %m");
908 if (cwd_st.st_dev != dev_st.st_rdev)
909 die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
912 .dqb_bhardlimit = block_quota,
913 .dqb_bsoftlimit = block_quota,
914 .dqb_ihardlimit = inode_quota,
915 .dqb_isoftlimit = inode_quota,
916 .dqb_valid = QIF_LIMITS,
918 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
919 die("Cannot set disk quota: %m");
920 msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
925 /*** The keeper process ***/
928 signal_alarm(int unused UNUSED)
930 /* Time limit checks are synchronous, so we only schedule them there. */
936 signal_int(int unused UNUSED)
938 /* Interrupts are fatal, so no synchronization requirements. */
939 meta_printf("exitsig:%d\n", SIGINT);
940 err("SG: Interrupted");
943 #define PROC_BUF_SIZE 4096
945 read_proc_file(char *buf, char *name, int *fdp)
951 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
952 *fdp = open(buf, O_RDONLY);
954 die("open(%s): %m", buf);
956 lseek(*fdp, 0, SEEK_SET);
957 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
958 die("read on /proc/$pid/%s: %m", name);
959 if (c >= PROC_BUF_SIZE-1)
960 die("/proc/$pid/%s too long", name);
965 get_wall_time_ms(void)
967 struct timeval now, wall;
968 gettimeofday(&now, NULL);
969 timersub(&now, &start_time, &wall);
970 return wall.tv_sec*1000 + wall.tv_usec/1000;
974 get_run_time_ms(struct rusage *rus)
977 return cg_get_run_time_ms();
981 struct timeval total;
982 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
983 return total.tv_sec*1000 + total.tv_usec/1000;
986 char buf[PROC_BUF_SIZE], *x;
988 static int proc_stat_fd;
990 read_proc_file(buf, "stat", &proc_stat_fd);
992 while (*x && *x != ' ')
997 die("proc stat syntax error 1");
998 while (*x && (*x != ')' || x[1] != ' '))
1000 while (*x == ')' || *x == ' ')
1002 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1003 die("proc stat syntax error 2");
1005 return (utime + stime) * 1000 / ticks_per_sec;
1013 int wall_ms = get_wall_time_ms();
1014 if (wall_ms > wall_timeout)
1015 err("TO: Time limit exceeded (wall clock)");
1017 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1021 int ms = get_run_time_ms(NULL);
1023 fprintf(stderr, "[time check: %d msec]\n", ms);
1024 if (ms > timeout && ms > extra_timeout)
1025 err("TO: Time limit exceeded");
1032 read_errors_from_fd = error_pipes[0];
1033 close(error_pipes[1]);
1035 struct sigaction sa;
1036 bzero(&sa, sizeof(sa));
1037 sa.sa_handler = signal_int;
1038 sigaction(SIGINT, &sa, NULL);
1040 gettimeofday(&start_time, NULL);
1041 ticks_per_sec = sysconf(_SC_CLK_TCK);
1042 if (ticks_per_sec <= 0)
1043 die("Invalid ticks_per_sec!");
1045 if (timeout || wall_timeout)
1047 sa.sa_handler = signal_alarm;
1048 sigaction(SIGALRM, &sa, NULL);
1062 p = wait4(box_pid, &stat, 0, &rus);
1070 die("wait4: unknown pid %d exited!", p);
1073 // Check error pipe if there is an internal error passed from inside the box
1075 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1082 if (WIFEXITED(stat))
1085 if (WEXITSTATUS(stat))
1087 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1088 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1090 if (timeout && total_ms > timeout)
1091 err("TO: Time limit exceeded");
1092 if (wall_timeout && wall_ms > wall_timeout)
1093 err("TO: Time limit exceeded (wall clock)");
1095 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1096 total_ms/1000, total_ms%1000,
1097 wall_ms/1000, wall_ms%1000);
1100 else if (WIFSIGNALED(stat))
1102 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1104 err("SG: Caught fatal signal %d", WTERMSIG(stat));
1106 else if (WIFSTOPPED(stat))
1108 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1110 err("SG: Stopped by signal %d", WSTOPSIG(stat));
1113 die("wait4: unknown status %x, giving up!", stat);
1117 /*** The process running inside the box ***/
1122 if (mkdir("root", 0750) < 0 && errno != EEXIST)
1123 die("mkdir('root'): %m");
1125 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1126 die("Cannot mount root ramdisk: %m");
1130 if (chroot("root") < 0)
1131 die("Chroot failed: %m");
1133 if (chdir("root/box") < 0)
1134 die("Cannot change current directory: %m");
1138 setup_credentials(void)
1140 if (setresgid(box_gid, box_gid, box_gid) < 0)
1141 die("setresgid: %m");
1142 if (setgroups(0, NULL) < 0)
1143 die("setgroups: %m");
1144 if (setresuid(box_uid, box_uid, box_uid) < 0)
1145 die("setresuid: %m");
1155 if (open(redir_stdin, O_RDONLY) != 0)
1156 die("open(\"%s\"): %m", redir_stdin);
1161 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1162 die("open(\"%s\"): %m", redir_stdout);
1167 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1168 die("open(\"%s\"): %m", redir_stderr);
1175 setup_rlim(const char *res_name, int res, rlim_t limit)
1177 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1178 if (setrlimit(res, &rl) < 0)
1179 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1185 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1188 RLIM(AS, memory_limit * 1024);
1190 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1195 RLIM(NPROC, max_processes);
1201 box_inside(void *arg)
1204 write_errors_to_fd = error_pipes[1];
1205 close(error_pipes[0]);
1209 setup_credentials();
1212 char **env = setup_environment();
1214 if (set_cwd && chdir(set_cwd))
1217 execve(args[0], args, env);
1218 die("execve(\"%s\"): %m", args[0]);
1224 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1225 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1226 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1227 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1229 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1231 if (chdir(box_dir) < 0)
1232 die("chdir(%s): %m", box_dir);
1240 msg("Preparing sandbox directory\n");
1241 xsystem("rm -rf box");
1242 if (mkdir("box", 0700) < 0)
1243 die("Cannot create box: %m");
1244 if (chown("box", orig_uid, orig_gid) < 0)
1245 die("Cannot chown box: %m");
1256 if (!dir_exists("box"))
1257 die("Box directory not found, there isn't anything to clean up");
1259 msg("Deleting sandbox directory\n");
1260 xsystem("rm -rf *");
1261 if (rmdir(box_dir) < 0)
1262 die("Cannot remove %s: %m", box_dir);
1269 if (!dir_exists("box"))
1270 die("Box directory not found, did you run `isolate --init'?");
1273 snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", box_uid, box_gid);
1275 snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
1277 if (pipe(error_pipes) < 0)
1279 for (int i=0; i<2; i++)
1280 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1281 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1282 die("fcntl on pipe: %m");
1285 box_inside, // Function to execute as the body of the new process
1286 argv, // Pass our stack
1287 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1288 argv); // Pass the arguments
1292 die("clone returned 0");
1299 printf("Process isolator 1.0\n");
1300 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1301 printf("\nCompile-time configuration:\n");
1302 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1303 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1304 CONFIG_ISOLATE_FIRST_UID,
1305 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1306 CONFIG_ISOLATE_FIRST_GID,
1307 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1312 static void __attribute__((format(printf,1,2)))
1313 usage(const char *msg, ...)
1318 va_start(args, msg);
1319 vfprintf(stderr, msg, args);
1323 Usage: isolate [<options>] <command>\n\
1326 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1327 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1328 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1329 --cg-timing\t\tTime limits affects total run time of the control group\n\
1330 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1331 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1332 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1333 --dir=...:<opt>\tSpecify options for a rule:\n\
1334 \t\t\t\tdev\tAllow access to special files\n\
1335 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1336 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1337 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1338 \t\t\t\trw\tAllow read-write access\n\
1339 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1340 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1341 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1342 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1343 -e, --full-env\t\tInherit full environment of the parent process\n\
1344 -m, --mem=<size>\tLimit address space to <size> KB\n\
1345 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1346 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1347 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1348 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1349 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1350 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1351 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1352 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1353 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1354 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1357 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1358 --run -- <cmd> ...\tRun given command within sandbox\n\
1359 --cleanup\t\tClean up sandbox\n\
1360 --version\t\tDisplay program version and configuration\n\
1375 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1377 static const struct option long_opts[] = {
1378 { "box-id", 1, NULL, 'b' },
1379 { "chdir", 1, NULL, 'c' },
1380 { "cg", 0, NULL, OPT_CG },
1381 { "cg-mem", 1, NULL, OPT_CG_MEM },
1382 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1383 { "cleanup", 0, NULL, OPT_CLEANUP },
1384 { "dir", 1, NULL, 'd' },
1385 { "env", 1, NULL, 'E' },
1386 { "extra-time", 1, NULL, 'x' },
1387 { "full-env", 0, NULL, 'e' },
1388 { "init", 0, NULL, OPT_INIT },
1389 { "mem", 1, NULL, 'm' },
1390 { "meta", 1, NULL, 'M' },
1391 { "processes", 2, NULL, 'p' },
1392 { "quota", 1, NULL, 'q' },
1393 { "run", 0, NULL, OPT_RUN },
1394 { "stack", 1, NULL, 'k' },
1395 { "stderr", 1, NULL, 'r' },
1396 { "stdin", 1, NULL, 'i' },
1397 { "stdout", 1, NULL, 'o' },
1398 { "time", 1, NULL, 't' },
1399 { "verbose", 0, NULL, 'v' },
1400 { "version", 0, NULL, OPT_VERSION },
1401 { "wall-time", 1, NULL, 'w' },
1402 { NULL, 0, NULL, 0 }
1406 main(int argc, char **argv)
1410 enum opt_code mode = 0;
1414 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1418 box_id = atoi(optarg);
1427 if (!set_dir_action(optarg))
1428 usage("Invalid directory specified: %s\n", optarg);
1434 if (!set_env_action(optarg))
1435 usage("Invalid environment specified: %s\n", optarg);
1438 stack_limit = atoi(optarg);
1441 redir_stdin = optarg;
1444 memory_limit = atoi(optarg);
1450 redir_stdout = optarg;
1454 max_processes = atoi(optarg);
1459 sep = strchr(optarg, ',');
1461 usage("Invalid quota specified: %s\n", optarg);
1462 block_quota = atoi(optarg);
1463 inode_quota = atoi(sep+1);
1466 redir_stderr = optarg;
1469 timeout = 1000*atof(optarg);
1475 wall_timeout = 1000*atof(optarg);
1478 extra_timeout = 1000*atof(optarg);
1484 if (!mode || mode == c)
1487 usage("Only one command is allowed.\n");
1490 cg_memory_limit = atoi(optarg);
1500 usage("Please specify an isolate command (e.g. --init, --run).\n");
1501 if (mode == OPT_VERSION)
1508 die("Must be started as root");
1509 orig_uid = getuid();
1510 orig_gid = getgid();
1520 usage("--init mode takes no parameters\n");
1525 usage("--run mode requires a command to run\n");
1530 usage("--cleanup mode takes no parameters\n");
1534 die("Internal error: mode mismatch");