2 * A Process Isolator based on Linux Containers
4 * (c) 2012-2014 Martin Mares <mj@ucw.cz>
5 * (c) 2012-2014 Bernard Blackham <bernard@blackham.com.au>
29 #include <sys/signal.h>
30 #include <sys/resource.h>
31 #include <sys/mount.h>
33 #include <sys/quota.h>
36 #define NONRET __attribute__((noreturn))
37 #define UNUSED __attribute__((unused))
38 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
40 static int timeout; /* milliseconds */
41 static int wall_timeout;
42 static int extra_timeout;
43 static int pass_environ;
45 static int memory_limit;
46 static int stack_limit;
47 static int block_quota;
48 static int inode_quota;
49 static int max_processes = 1;
50 static char *redir_stdin, *redir_stdout, *redir_stderr;
54 static int cg_memory_limit;
58 static char box_dir[1024];
63 static uid_t orig_uid;
64 static gid_t orig_gid;
66 static int partial_line;
67 static int cleanup_ownership;
69 static struct timeval start_time;
70 static int ticks_per_sec;
71 static int total_ms, wall_ms;
72 static volatile sig_atomic_t timer_tick;
74 static int error_pipes[2];
75 static int write_errors_to_fd;
76 static int read_errors_from_fd;
78 static void die(char *msg, ...) NONRET;
79 static void cg_stats(void);
80 static int get_wall_time_ms(void);
81 static int get_run_time_ms(struct rusage *rus);
83 static void chowntree(char *path, uid_t uid, gid_t gid);
87 static FILE *metafile;
90 meta_open(const char *name)
92 if (!strcmp(name, "-"))
97 metafile = fopen(name, "w");
99 die("Failed to open metafile '%s'",name);
105 if (metafile && metafile != stdout)
109 static void __attribute__((format(printf,1,2)))
110 meta_printf(const char *fmt, ...)
117 vfprintf(metafile, fmt, args);
122 final_stats(struct rusage *rus)
124 total_ms = get_run_time_ms(rus);
125 wall_ms = get_wall_time_ms();
127 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
128 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
129 meta_printf("max-rss:%ld\n", rus->ru_maxrss);
130 meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
131 meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
136 /*** Messages and exits ***/
143 kill(-box_pid, SIGKILL);
144 kill(box_pid, SIGKILL);
145 meta_printf("killed:1\n");
150 p = wait4(box_pid, &stat, 0, &rus);
151 while (p < 0 && errno == EINTR);
153 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
158 if (rc < 2 && cleanup_ownership)
159 chowntree("box", orig_uid, orig_gid);
173 /* Report an error of the sandbox itself */
174 static void NONRET __attribute__((format(printf,1,2)))
180 int n = vsnprintf(buf, sizeof(buf), msg, args);
182 if (write_errors_to_fd)
184 // We are inside the box, have to use error pipe for error reporting.
185 // We hope that the whole error message fits in PIPE_BUF bytes.
186 write(write_errors_to_fd, buf, n);
190 // Otherwise, we in the box keeper process, so we report errors normally
192 meta_printf("status:XX\nmessage:%s\n", buf);
198 /* Report an error of the program inside the sandbox */
199 static void NONRET __attribute__((format(printf,1,2)))
205 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
207 meta_printf("status:%c%c\n", msg[0], msg[1]);
211 vsnprintf(buf, sizeof(buf), msg, args);
212 meta_printf("message:%s\n", buf);
218 /* Write a message, but only if in verbose mode */
219 static void __attribute__((format(printf,1,2)))
226 int len = strlen(msg);
228 partial_line = (msg[len-1] != '\n');
229 vfprintf(stderr, msg, args);
235 /*** Utility functions ***/
240 void *p = malloc(size);
242 die("Out of memory");
249 char *p = strdup(str);
251 die("Out of memory");
255 static int dir_exists(char *path)
258 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
261 static int rmtree_helper(const char *fpath, const struct stat *sb,
262 int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
264 if (S_ISDIR(sb->st_mode))
266 if (rmdir(fpath) < 0)
267 die("Cannot rmdir %s: %m", fpath);
271 if (unlink(fpath) < 0)
272 die("Cannot unlink %s: %m", fpath);
280 nftw(path, rmtree_helper, 32, FTW_MOUNT | FTW_PHYS | FTW_DEPTH);
283 static uid_t chown_uid;
284 static gid_t chown_gid;
286 static int chowntree_helper(const char *fpath, const struct stat *sb UNUSED,
287 int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
289 if (lchown(fpath, chown_uid, chown_gid) < 0)
290 die("Cannot chown %s: %m", fpath);
296 chowntree(char *path, uid_t uid, gid_t gid)
300 nftw(path, chowntree_helper, 32, FTW_MOUNT | FTW_PHYS);
303 /*** Environment rules ***/
306 char *var; // Variable to match
307 char *val; // ""=clear, NULL=inherit
309 struct env_rule *next;
312 static struct env_rule *first_env_rule;
313 static struct env_rule **last_env_rule = &first_env_rule;
315 static struct env_rule default_env_rules[] = {
316 { "LIBC_FATAL_STDERR_", "1" }
320 set_env_action(char *a0)
322 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
323 char *a = (char *)(r+1);
326 char *sep = strchr(a, '=');
338 last_env_rule = &r->next;
344 match_env_var(char *env_entry, struct env_rule *r)
346 if (strncmp(env_entry, r->var, r->var_len))
348 return (env_entry[r->var_len] == '=');
352 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
354 // First remove the variable if already set
356 while (pos < *env_sizep && !match_env_var(env[pos], r))
358 if (pos < *env_sizep)
361 env[pos] = env[*env_sizep];
362 env[*env_sizep] = NULL;
365 // What is the new value?
371 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
372 sprintf(new, "%s=%s", r->var, r->val);
377 while (environ[pos] && !match_env_var(environ[pos], r))
379 if (!(new = environ[pos]))
383 // Add it at the end of the array
384 env[(*env_sizep)++] = new;
385 env[*env_sizep] = NULL;
389 setup_environment(void)
391 // Link built-in rules with user rules
392 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
394 default_env_rules[i].next = first_env_rule;
395 first_env_rule = &default_env_rules[i];
398 // Scan the original environment
399 char **orig_env = environ;
401 while (orig_env[orig_size])
404 // For each rule, reserve one more slot and calculate length
406 for (struct env_rule *r = first_env_rule; r; r=r->next)
409 r->var_len = strlen(r->var);
412 // Create a new environment
413 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
417 memcpy(env, environ, orig_size * sizeof(char *));
424 // Apply the rules one by one
425 for (struct env_rule *r = first_env_rule; r; r=r->next)
426 apply_env_rule(env, &size, r);
428 // Return the new env and pass some gossip
431 fprintf(stderr, "Passing environment:\n");
432 for (int i=0; env[i]; i++)
433 fprintf(stderr, "\t%s\n", env[i]);
438 /*** Directory rules ***/
441 char *inside; // A relative path
442 char *outside; // This can be an absolute path or a relative path starting with "./"
443 unsigned int flags; // DIR_FLAG_xxx
444 struct dir_rule *next;
447 enum dir_rule_flags {
455 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
457 static struct dir_rule *first_dir_rule;
458 static struct dir_rule **last_dir_rule = &first_dir_rule;
460 static int add_dir_rule(char *in, char *out, unsigned int flags)
462 // Make sure that "in" is relative
469 if (flags & DIR_FLAG_FS)
471 if (!out || out[0] == '/')
476 if (out && out[0] != '/' && strncmp(out, "./", 2))
480 // Override an existing rule
482 for (r = first_dir_rule; r; r = r->next)
483 if (!strcmp(r->inside, in))
489 r = xmalloc(sizeof(*r));
492 last_dir_rule = &r->next;
500 static unsigned int parse_dir_option(char *opt)
502 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
503 if (!strcmp(opt, dir_flag_names[i]))
505 die("Unknown directory option %s", opt);
508 static int set_dir_action(char *arg)
512 char *colon = strchr(arg, ':');
513 unsigned int flags = 0;
517 char *next = strchr(colon, ':');
520 flags |= parse_dir_option(colon);
524 char *eq = strchr(arg, '=');
528 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
532 char *out = xmalloc(1 + strlen(arg) + 1);
533 sprintf(out, "/%s", arg);
534 return add_dir_rule(arg, out, flags);
538 static void init_dir_rules(void)
540 set_dir_action("box=./box:rw");
541 set_dir_action("bin");
542 set_dir_action("dev:dev");
543 set_dir_action("lib");
544 set_dir_action("lib64:maybe");
545 set_dir_action("proc=proc:fs");
546 set_dir_action("usr");
549 static void make_dir(char *path)
551 char *sep = (path[0] == '/' ? path+1 : path);
555 sep = strchr(sep, '/');
559 if (!dir_exists(path) && mkdir(path, 0777) < 0)
560 die("Cannot create directory %s: %m\n", path);
568 static void apply_dir_rules(void)
570 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
572 char *in = r->inside;
573 char *out = r->outside;
576 msg("Not binding anything on %s\n", r->inside);
580 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
582 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
587 snprintf(root_in, sizeof(root_in), "root/%s", in);
590 unsigned long mount_flags = 0;
591 if (!(r->flags & DIR_FLAG_RW))
592 mount_flags |= MS_RDONLY;
593 if (r->flags & DIR_FLAG_NOEXEC)
594 mount_flags |= MS_NOEXEC;
595 if (!(r->flags & DIR_FLAG_DEV))
596 mount_flags |= MS_NODEV;
598 if (r->flags & DIR_FLAG_FS)
600 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
601 if (mount("none", root_in, out, mount_flags, "") < 0)
602 die("Cannot mount %s on %s: %m", out, in);
606 mount_flags |= MS_BIND | MS_NOSUID;
607 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
608 // Most mount flags need remount to work
609 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
610 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
611 die("Cannot mount %s on %s: %m", out, in);
616 /*** Control groups ***/
618 struct cg_controller_desc {
630 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
631 [CG_MEMORY] = { "memory", 0 },
632 [CG_CPUACCT] = { "cpuacct", 0 },
633 [CG_CPUSET] = { "cpuset", 1 },
634 [CG_NUM_CONTROLLERS] = { NULL, 0 },
637 #define FOREACH_CG_CONTROLLER(_controller) \
638 for (cg_controller (_controller) = 0; \
639 (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
641 static const char *cg_controller_name(cg_controller c)
643 return cg_controllers[c].name;
646 static int cg_controller_optional(cg_controller c)
648 return cg_controllers[c].optional;
651 static char cg_name[256];
653 #define CG_BUFSIZE 1024
656 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
658 const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
659 snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
663 cg_read(cg_controller controller, const char *attr, char *buf)
673 cg_makepath(path, sizeof(path), controller, attr);
675 int fd = open(path, O_RDONLY);
680 die("Cannot read %s: %m", path);
683 int n = read(fd, buf, CG_BUFSIZE);
688 die("Cannot read %s: %m", path);
690 if (n >= CG_BUFSIZE - 1)
691 die("Attribute %s too long", path);
692 if (n > 0 && buf[n-1] == '\n')
697 msg("CG: Read %s = %s\n", attr, buf);
703 static void __attribute__((format(printf,3,4)))
704 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
716 char buf[CG_BUFSIZE];
717 int n = vsnprintf(buf, sizeof(buf), fmt, args);
719 die("cg_write: Value for attribute %s is too long", attr);
722 msg("CG: Write %s = %s", attr, buf);
725 cg_makepath(path, sizeof(path), controller, attr);
727 int fd = open(path, O_WRONLY | O_TRUNC);
733 die("Cannot write %s: %m", path);
736 int written = write(fd, buf, n);
742 die("Cannot set %s to %s: %m", path, buf);
745 die("Short write to %s (%d out of %d bytes)", path, written, n);
757 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
758 if (!dir_exists(cg_root))
759 die("Control group filesystem at %s not mounted", cg_root);
761 snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
762 msg("Using control group %s\n", cg_name);
772 char buf[CG_BUFSIZE];
775 FOREACH_CG_CONTROLLER(controller)
777 cg_makepath(path, sizeof(path), controller, "");
778 if (stat(path, &st) >= 0 || errno != ENOENT)
780 msg("Control group %s already exists, trying to empty it.\n", path);
782 die("Failed to reset control group %s: %m", path);
785 if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
786 die("Failed to create control group %s: %m", path);
789 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
790 if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
791 cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
792 if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
793 cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
802 msg("Entering control group %s\n", cg_name);
804 FOREACH_CG_CONTROLLER(controller)
806 if (cg_controller_optional(controller))
807 cg_write(controller, "?tasks", "%d\n", (int) getpid());
809 cg_write(controller, "tasks", "%d\n", (int) getpid());
814 cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
815 cg_write(CG_MEMORY, "?memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
819 cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
823 cg_get_run_time_ms(void)
828 char buf[CG_BUFSIZE];
829 cg_read(CG_CPUACCT, "cpuacct.usage", buf);
830 unsigned long long ns = atoll(buf);
840 char buf[CG_BUFSIZE];
842 // Memory usage statistics
843 unsigned long long mem=0, memsw=0;
844 if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
846 if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
853 meta_printf("cg-mem:%lld\n", mem >> 10);
859 char buf[CG_BUFSIZE];
864 FOREACH_CG_CONTROLLER(controller)
866 if (cg_controller_optional(controller))
868 if (!cg_read(controller, "?tasks", buf))
872 cg_read(controller, "tasks", buf);
875 die("Some tasks left in controller %s of cgroup %s, failed to remove it",
876 cg_controller_name(controller), cg_name);
879 cg_makepath(path, sizeof(path), controller, "");
882 die("Cannot remove control group %s: %m", path);
886 /*** Disk quotas ***/
889 path_begins_with(char *path, char *with)
892 if (*path++ != *with++)
894 return (!*with || *with == '/');
898 find_device(char *path)
900 FILE *f = setmntent("/proc/mounts", "r");
902 die("Cannot open /proc/mounts: %m");
906 char *best_dev = NULL;
907 while (me = getmntent(f))
909 if (!path_begins_with(me->mnt_fsname, "/dev"))
911 if (path_begins_with(path, me->mnt_dir))
913 int len = strlen(me->mnt_dir);
918 best_dev = xstrdup(me->mnt_fsname);
933 if (!getcwd(cwd, sizeof(cwd)))
936 char *dev = find_device(cwd);
938 die("Cannot identify filesystem which contains %s", cwd);
939 msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
942 struct stat dev_st, cwd_st;
943 if (stat(dev, &dev_st) < 0)
944 die("Cannot identify block device %s: %m", dev);
945 if (!S_ISBLK(dev_st.st_mode))
946 die("Expected that %s is a block device", dev);
947 if (stat(".", &cwd_st) < 0)
948 die("Cannot stat cwd: %m");
949 if (cwd_st.st_dev != dev_st.st_rdev)
950 die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
953 .dqb_bhardlimit = block_quota,
954 .dqb_bsoftlimit = block_quota,
955 .dqb_ihardlimit = inode_quota,
956 .dqb_isoftlimit = inode_quota,
957 .dqb_valid = QIF_LIMITS,
959 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
960 die("Cannot set disk quota: %m");
961 msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
966 /*** The keeper process ***/
969 signal_alarm(int unused UNUSED)
971 /* Time limit checks are synchronous, so we only schedule them there. */
977 signal_int(int unused UNUSED)
979 /* Interrupts are fatal, so no synchronization requirements. */
980 meta_printf("exitsig:%d\n", SIGINT);
981 err("SG: Interrupted");
984 #define PROC_BUF_SIZE 4096
986 read_proc_file(char *buf, char *name, int *fdp)
992 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
993 *fdp = open(buf, O_RDONLY);
995 die("open(%s): %m", buf);
997 lseek(*fdp, 0, SEEK_SET);
998 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
999 die("read on /proc/$pid/%s: %m", name);
1000 if (c >= PROC_BUF_SIZE-1)
1001 die("/proc/$pid/%s too long", name);
1006 get_wall_time_ms(void)
1008 struct timeval now, wall;
1009 gettimeofday(&now, NULL);
1010 timersub(&now, &start_time, &wall);
1011 return wall.tv_sec*1000 + wall.tv_usec/1000;
1015 get_run_time_ms(struct rusage *rus)
1018 return cg_get_run_time_ms();
1022 struct timeval total;
1023 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
1024 return total.tv_sec*1000 + total.tv_usec/1000;
1027 char buf[PROC_BUF_SIZE], *x;
1029 static int proc_stat_fd;
1031 read_proc_file(buf, "stat", &proc_stat_fd);
1033 while (*x && *x != ' ')
1038 die("proc stat syntax error 1");
1039 while (*x && (*x != ')' || x[1] != ' '))
1041 while (*x == ')' || *x == ' ')
1043 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1044 die("proc stat syntax error 2");
1046 return (utime + stime) * 1000 / ticks_per_sec;
1054 int wall_ms = get_wall_time_ms();
1055 if (wall_ms > wall_timeout)
1056 err("TO: Time limit exceeded (wall clock)");
1058 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1062 int ms = get_run_time_ms(NULL);
1064 fprintf(stderr, "[time check: %d msec]\n", ms);
1065 if (ms > timeout && ms > extra_timeout)
1066 err("TO: Time limit exceeded");
1073 read_errors_from_fd = error_pipes[0];
1074 close(error_pipes[1]);
1076 struct sigaction sa;
1077 bzero(&sa, sizeof(sa));
1078 sa.sa_handler = signal_int;
1079 sigaction(SIGINT, &sa, NULL);
1081 gettimeofday(&start_time, NULL);
1082 ticks_per_sec = sysconf(_SC_CLK_TCK);
1083 if (ticks_per_sec <= 0)
1084 die("Invalid ticks_per_sec!");
1086 if (timeout || wall_timeout)
1088 sa.sa_handler = signal_alarm;
1089 sigaction(SIGALRM, &sa, NULL);
1103 p = wait4(box_pid, &stat, 0, &rus);
1111 die("wait4: unknown pid %d exited!", p);
1114 // Check error pipe if there is an internal error passed from inside the box
1116 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1123 if (WIFEXITED(stat))
1126 if (WEXITSTATUS(stat))
1128 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1129 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1131 if (timeout && total_ms > timeout)
1132 err("TO: Time limit exceeded");
1133 if (wall_timeout && wall_ms > wall_timeout)
1134 err("TO: Time limit exceeded (wall clock)");
1136 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1137 total_ms/1000, total_ms%1000,
1138 wall_ms/1000, wall_ms%1000);
1141 else if (WIFSIGNALED(stat))
1143 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1145 err("SG: Caught fatal signal %d", WTERMSIG(stat));
1147 else if (WIFSTOPPED(stat))
1149 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1151 err("SG: Stopped by signal %d", WSTOPSIG(stat));
1154 die("wait4: unknown status %x, giving up!", stat);
1158 /*** The process running inside the box ***/
1163 if (mkdir("root", 0750) < 0 && errno != EEXIST)
1164 die("mkdir('root'): %m");
1166 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1167 die("Cannot mount root ramdisk: %m");
1171 if (chroot("root") < 0)
1172 die("Chroot failed: %m");
1174 if (chdir("root/box") < 0)
1175 die("Cannot change current directory: %m");
1179 setup_credentials(void)
1181 if (setresgid(box_gid, box_gid, box_gid) < 0)
1182 die("setresgid: %m");
1183 if (setgroups(0, NULL) < 0)
1184 die("setgroups: %m");
1185 if (setresuid(box_uid, box_uid, box_uid) < 0)
1186 die("setresuid: %m");
1196 if (open(redir_stdin, O_RDONLY) != 0)
1197 die("open(\"%s\"): %m", redir_stdin);
1202 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1203 die("open(\"%s\"): %m", redir_stdout);
1208 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1209 die("open(\"%s\"): %m", redir_stderr);
1216 setup_rlim(const char *res_name, int res, rlim_t limit)
1218 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1219 if (setrlimit(res, &rl) < 0)
1220 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1226 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1229 RLIM(AS, memory_limit * 1024);
1231 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1236 RLIM(NPROC, max_processes);
1242 box_inside(void *arg)
1245 write_errors_to_fd = error_pipes[1];
1246 close(error_pipes[0]);
1251 setup_credentials();
1254 char **env = setup_environment();
1256 if (set_cwd && chdir(set_cwd))
1259 execve(args[0], args, env);
1260 die("execve(\"%s\"): %m", args[0]);
1266 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1267 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1268 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1269 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1271 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1273 if (chdir(box_dir) < 0)
1274 die("chdir(%s): %m", box_dir);
1282 msg("Preparing sandbox directory\n");
1284 if (mkdir("box", 0700) < 0)
1285 die("Cannot create box: %m");
1286 if (chown("box", orig_uid, orig_gid) < 0)
1287 die("Cannot chown box: %m");
1298 if (!dir_exists("box"))
1299 die("Box directory not found, there isn't anything to clean up");
1301 msg("Deleting sandbox directory\n");
1309 if (!dir_exists("box"))
1310 die("Box directory not found, did you run `isolate --init'?");
1312 chowntree("box", box_uid, box_gid);
1313 cleanup_ownership = 1;
1315 if (pipe(error_pipes) < 0)
1317 for (int i=0; i<2; i++)
1318 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1319 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1320 die("fcntl on pipe: %m");
1323 box_inside, // Function to execute as the body of the new process
1324 argv, // Pass our stack
1325 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1326 argv); // Pass the arguments
1330 die("clone returned 0");
1337 printf("Process isolator 1.0\n");
1338 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1339 printf("\nCompile-time configuration:\n");
1340 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1341 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1342 CONFIG_ISOLATE_FIRST_UID,
1343 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1344 CONFIG_ISOLATE_FIRST_GID,
1345 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1350 static void __attribute__((format(printf,1,2)))
1351 usage(const char *msg, ...)
1356 va_start(args, msg);
1357 vfprintf(stderr, msg, args);
1361 Usage: isolate [<options>] <command>\n\
1364 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1365 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1366 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1367 --cg-timing\t\tTime limits affects total run time of the control group\n\
1368 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1369 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1370 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1371 --dir=...:<opt>\tSpecify options for a rule:\n\
1372 \t\t\t\tdev\tAllow access to special files\n\
1373 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1374 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1375 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1376 \t\t\t\trw\tAllow read-write access\n\
1377 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1378 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1379 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1380 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1381 -e, --full-env\t\tInherit full environment of the parent process\n\
1382 -m, --mem=<size>\tLimit address space to <size> KB\n\
1383 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1384 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1385 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1386 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1387 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1388 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1389 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1390 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1391 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1392 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1395 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1396 --run -- <cmd> ...\tRun given command within sandbox\n\
1397 --cleanup\t\tClean up sandbox\n\
1398 --version\t\tDisplay program version and configuration\n\
1413 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1415 static const struct option long_opts[] = {
1416 { "box-id", 1, NULL, 'b' },
1417 { "chdir", 1, NULL, 'c' },
1418 { "cg", 0, NULL, OPT_CG },
1419 { "cg-mem", 1, NULL, OPT_CG_MEM },
1420 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1421 { "cleanup", 0, NULL, OPT_CLEANUP },
1422 { "dir", 1, NULL, 'd' },
1423 { "env", 1, NULL, 'E' },
1424 { "extra-time", 1, NULL, 'x' },
1425 { "full-env", 0, NULL, 'e' },
1426 { "init", 0, NULL, OPT_INIT },
1427 { "mem", 1, NULL, 'm' },
1428 { "meta", 1, NULL, 'M' },
1429 { "processes", 2, NULL, 'p' },
1430 { "quota", 1, NULL, 'q' },
1431 { "run", 0, NULL, OPT_RUN },
1432 { "stack", 1, NULL, 'k' },
1433 { "stderr", 1, NULL, 'r' },
1434 { "stdin", 1, NULL, 'i' },
1435 { "stdout", 1, NULL, 'o' },
1436 { "time", 1, NULL, 't' },
1437 { "verbose", 0, NULL, 'v' },
1438 { "version", 0, NULL, OPT_VERSION },
1439 { "wall-time", 1, NULL, 'w' },
1440 { NULL, 0, NULL, 0 }
1444 main(int argc, char **argv)
1448 enum opt_code mode = 0;
1452 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1456 box_id = atoi(optarg);
1465 if (!set_dir_action(optarg))
1466 usage("Invalid directory specified: %s\n", optarg);
1472 if (!set_env_action(optarg))
1473 usage("Invalid environment specified: %s\n", optarg);
1476 stack_limit = atoi(optarg);
1479 redir_stdin = optarg;
1482 memory_limit = atoi(optarg);
1488 redir_stdout = optarg;
1492 max_processes = atoi(optarg);
1497 sep = strchr(optarg, ',');
1499 usage("Invalid quota specified: %s\n", optarg);
1500 block_quota = atoi(optarg);
1501 inode_quota = atoi(sep+1);
1504 redir_stderr = optarg;
1507 timeout = 1000*atof(optarg);
1513 wall_timeout = 1000*atof(optarg);
1516 extra_timeout = 1000*atof(optarg);
1522 if (!mode || (int) mode == c)
1525 usage("Only one command is allowed.\n");
1528 cg_memory_limit = atoi(optarg);
1538 usage("Please specify an isolate command (e.g. --init, --run).\n");
1539 if (mode == OPT_VERSION)
1546 die("Must be started as root");
1547 orig_uid = getuid();
1548 orig_gid = getgid();
1558 usage("--init mode takes no parameters\n");
1563 usage("--run mode requires a command to run\n");
1568 usage("--cleanup mode takes no parameters\n");
1572 die("Internal error: mode mismatch");