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)
160 chowntree("box", orig_uid, orig_gid);
175 /* Report an error of the sandbox itself */
176 static void NONRET __attribute__((format(printf,1,2)))
182 int n = vsnprintf(buf, sizeof(buf), msg, args);
184 if (write_errors_to_fd)
186 // We are inside the box, have to use error pipe for error reporting.
187 // We hope that the whole error message fits in PIPE_BUF bytes.
188 write(write_errors_to_fd, buf, n);
192 // Otherwise, we in the box keeper process, so we report errors normally
194 meta_printf("status:XX\nmessage:%s\n", buf);
200 /* Report an error of the program inside the sandbox */
201 static void NONRET __attribute__((format(printf,1,2)))
207 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
209 meta_printf("status:%c%c\n", msg[0], msg[1]);
213 vsnprintf(buf, sizeof(buf), msg, args);
214 meta_printf("message:%s\n", buf);
220 /* Write a message, but only if in verbose mode */
221 static void __attribute__((format(printf,1,2)))
228 int len = strlen(msg);
230 partial_line = (msg[len-1] != '\n');
231 vfprintf(stderr, msg, args);
237 /*** Utility functions ***/
242 void *p = malloc(size);
244 die("Out of memory");
251 char *p = strdup(str);
253 die("Out of memory");
257 static int dir_exists(char *path)
260 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
263 static int rmtree_helper(const char *fpath, const struct stat *sb,
264 int typeflag, struct FTW *ftwbuf)
266 if (S_ISDIR(sb->st_mode))
268 if (rmdir(fpath) < 0)
269 die("Cannot rmdir %s: %m", fpath);
273 if (unlink(fpath) < 0)
274 die("Cannot unlink %s: %m", fpath);
282 nftw(path, rmtree_helper, 32, FTW_MOUNT | FTW_PHYS | FTW_DEPTH);
285 static uid_t chown_uid;
286 static gid_t chown_gid;
287 static int chowntree_helper(const char *fpath, const struct stat *sb,
288 int typeflag, struct FTW *ftwbuf)
290 if (lchown(fpath, chown_uid, chown_gid) < 0)
291 die("Cannot chown %s: %m", fpath);
297 chowntree(char *path, uid_t uid, gid_t gid)
301 nftw(path, chowntree_helper, 32, FTW_MOUNT | FTW_PHYS);
304 /*** Environment rules ***/
307 char *var; // Variable to match
308 char *val; // ""=clear, NULL=inherit
310 struct env_rule *next;
313 static struct env_rule *first_env_rule;
314 static struct env_rule **last_env_rule = &first_env_rule;
316 static struct env_rule default_env_rules[] = {
317 { "LIBC_FATAL_STDERR_", "1" }
321 set_env_action(char *a0)
323 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
324 char *a = (char *)(r+1);
327 char *sep = strchr(a, '=');
339 last_env_rule = &r->next;
345 match_env_var(char *env_entry, struct env_rule *r)
347 if (strncmp(env_entry, r->var, r->var_len))
349 return (env_entry[r->var_len] == '=');
353 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
355 // First remove the variable if already set
357 while (pos < *env_sizep && !match_env_var(env[pos], r))
359 if (pos < *env_sizep)
362 env[pos] = env[*env_sizep];
363 env[*env_sizep] = NULL;
366 // What is the new value?
372 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
373 sprintf(new, "%s=%s", r->var, r->val);
378 while (environ[pos] && !match_env_var(environ[pos], r))
380 if (!(new = environ[pos]))
384 // Add it at the end of the array
385 env[(*env_sizep)++] = new;
386 env[*env_sizep] = NULL;
390 setup_environment(void)
392 // Link built-in rules with user rules
393 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
395 default_env_rules[i].next = first_env_rule;
396 first_env_rule = &default_env_rules[i];
399 // Scan the original environment
400 char **orig_env = environ;
402 while (orig_env[orig_size])
405 // For each rule, reserve one more slot and calculate length
407 for (struct env_rule *r = first_env_rule; r; r=r->next)
410 r->var_len = strlen(r->var);
413 // Create a new environment
414 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
418 memcpy(env, environ, orig_size * sizeof(char *));
425 // Apply the rules one by one
426 for (struct env_rule *r = first_env_rule; r; r=r->next)
427 apply_env_rule(env, &size, r);
429 // Return the new env and pass some gossip
432 fprintf(stderr, "Passing environment:\n");
433 for (int i=0; env[i]; i++)
434 fprintf(stderr, "\t%s\n", env[i]);
439 /*** Directory rules ***/
442 char *inside; // A relative path
443 char *outside; // This can be an absolute path or a relative path starting with "./"
444 unsigned int flags; // DIR_FLAG_xxx
445 struct dir_rule *next;
448 enum dir_rule_flags {
456 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
458 static struct dir_rule *first_dir_rule;
459 static struct dir_rule **last_dir_rule = &first_dir_rule;
461 static int add_dir_rule(char *in, char *out, unsigned int flags)
463 // Make sure that "in" is relative
470 if (flags & DIR_FLAG_FS)
472 if (!out || out[0] == '/')
477 if (out && out[0] != '/' && strncmp(out, "./", 2))
481 // Override an existing rule
483 for (r = first_dir_rule; r; r = r->next)
484 if (!strcmp(r->inside, in))
490 r = xmalloc(sizeof(*r));
493 last_dir_rule = &r->next;
501 static unsigned int parse_dir_option(char *opt)
503 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
504 if (!strcmp(opt, dir_flag_names[i]))
506 die("Unknown directory option %s", opt);
509 static int set_dir_action(char *arg)
513 char *colon = strchr(arg, ':');
514 unsigned int flags = 0;
518 char *next = strchr(colon, ':');
521 flags |= parse_dir_option(colon);
525 char *eq = strchr(arg, '=');
529 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
533 char *out = xmalloc(1 + strlen(arg) + 1);
534 sprintf(out, "/%s", arg);
535 return add_dir_rule(arg, out, flags);
539 static void init_dir_rules(void)
541 set_dir_action("box=./box:rw");
542 set_dir_action("bin");
543 set_dir_action("dev:dev");
544 set_dir_action("lib");
545 set_dir_action("lib64:maybe");
546 set_dir_action("proc=proc:fs");
547 set_dir_action("usr");
550 static void make_dir(char *path)
552 char *sep = (path[0] == '/' ? path+1 : path);
556 sep = strchr(sep, '/');
560 if (!dir_exists(path) && mkdir(path, 0777) < 0)
561 die("Cannot create directory %s: %m\n", path);
569 static void apply_dir_rules(void)
571 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
573 char *in = r->inside;
574 char *out = r->outside;
577 msg("Not binding anything on %s\n", r->inside);
581 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
583 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
588 snprintf(root_in, sizeof(root_in), "root/%s", in);
591 unsigned long mount_flags = 0;
592 if (!(r->flags & DIR_FLAG_RW))
593 mount_flags |= MS_RDONLY;
594 if (r->flags & DIR_FLAG_NOEXEC)
595 mount_flags |= MS_NOEXEC;
596 if (!(r->flags & DIR_FLAG_DEV))
597 mount_flags |= MS_NODEV;
599 if (r->flags & DIR_FLAG_FS)
601 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
602 if (mount("none", root_in, out, mount_flags, "") < 0)
603 die("Cannot mount %s on %s: %m", out, in);
607 mount_flags |= MS_BIND | MS_NOSUID;
608 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
609 // Most mount flags need remount to work
610 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
611 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
612 die("Cannot mount %s on %s: %m", out, in);
617 /*** Control groups ***/
619 struct cg_controller_desc {
631 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
632 [CG_MEMORY] = { "memory", 0 },
633 [CG_CPUACCT] = { "cpuacct", 0 },
634 [CG_CPUSET] = { "cpuset", 1 },
635 [CG_NUM_CONTROLLERS] = { NULL, 0 },
638 #define FOREACH_CG_CONTROLLER(_controller) \
639 for (cg_controller (_controller) = 0; \
640 (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
642 static const char *cg_controller_name(cg_controller c)
644 return cg_controllers[c].name;
647 static const int cg_controller_optional(cg_controller c)
649 return cg_controllers[c].optional;
652 static char cg_name[256];
654 #define CG_BUFSIZE 1024
657 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
659 const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
660 snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
664 cg_read(cg_controller controller, const char *attr, char *buf)
674 cg_makepath(path, sizeof(path), controller, attr);
676 int fd = open(path, O_RDONLY);
681 die("Cannot read %s: %m", path);
684 int n = read(fd, buf, CG_BUFSIZE);
689 die("Cannot read %s: %m", path);
691 if (n >= CG_BUFSIZE - 1)
692 die("Attribute %s too long", path);
693 if (n > 0 && buf[n-1] == '\n')
698 msg("CG: Read %s = %s\n", attr, buf);
704 static void __attribute__((format(printf,3,4)))
705 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
717 char buf[CG_BUFSIZE];
718 int n = vsnprintf(buf, sizeof(buf), fmt, args);
720 die("cg_write: Value for attribute %s is too long", attr);
723 msg("CG: Write %s = %s", attr, buf);
726 cg_makepath(path, sizeof(path), controller, attr);
728 int fd = open(path, O_WRONLY | O_TRUNC);
734 die("Cannot write %s: %m", path);
737 int written = write(fd, buf, n);
743 die("Cannot set %s to %s: %m", path, buf);
746 die("Short write to %s (%d out of %d bytes)", path, written, n);
758 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
759 if (!dir_exists(cg_root))
760 die("Control group filesystem at %s not mounted", cg_root);
762 snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
763 msg("Using control group %s\n", cg_name);
773 char buf[CG_BUFSIZE];
776 FOREACH_CG_CONTROLLER(controller)
778 cg_makepath(path, sizeof(path), controller, "");
779 if (stat(path, &st) >= 0 || errno != ENOENT)
781 msg("Control group %s already exists, trying to empty it.\n", path);
783 die("Failed to reset control group %s: %m", path);
786 if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
787 die("Failed to create control group %s: %m", path);
790 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
791 if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
792 cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
793 if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
794 cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
803 msg("Entering control group %s\n", cg_name);
805 FOREACH_CG_CONTROLLER(controller)
807 if (cg_controller_optional(controller))
808 cg_write(controller, "?tasks", "%d\n", (int) getpid());
810 cg_write(controller, "tasks", "%d\n", (int) getpid());
815 cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
816 cg_write(CG_MEMORY, "?memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
820 cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
824 cg_get_run_time_ms(void)
829 char buf[CG_BUFSIZE];
830 cg_read(CG_CPUACCT, "cpuacct.usage", buf);
831 unsigned long long ns = atoll(buf);
841 char buf[CG_BUFSIZE];
843 // Memory usage statistics
844 unsigned long long mem=0, memsw=0;
845 if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
847 if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
854 meta_printf("cg-mem:%lld\n", mem >> 10);
860 char buf[CG_BUFSIZE];
865 FOREACH_CG_CONTROLLER(controller)
867 if (cg_controller_optional(controller)) {
868 if (!cg_read(controller, "?tasks", buf))
871 cg_read(controller, "tasks", buf);
874 die("Some tasks left in controller %s of cgroup %s, failed to remove it",
875 cg_controller_name(controller), cg_name);
878 cg_makepath(path, sizeof(path), controller, "");
881 die("Cannot remove control group %s: %m", path);
885 /*** Disk quotas ***/
888 path_begins_with(char *path, char *with)
891 if (*path++ != *with++)
893 return (!*with || *with == '/');
897 find_device(char *path)
899 FILE *f = setmntent("/proc/mounts", "r");
901 die("Cannot open /proc/mounts: %m");
905 char *best_dev = NULL;
906 while (me = getmntent(f))
908 if (!path_begins_with(me->mnt_fsname, "/dev"))
910 if (path_begins_with(path, me->mnt_dir))
912 int len = strlen(me->mnt_dir);
917 best_dev = xstrdup(me->mnt_fsname);
932 if (!getcwd(cwd, sizeof(cwd)))
935 char *dev = find_device(cwd);
937 die("Cannot identify filesystem which contains %s", cwd);
938 msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
941 struct stat dev_st, cwd_st;
942 if (stat(dev, &dev_st) < 0)
943 die("Cannot identify block device %s: %m", dev);
944 if (!S_ISBLK(dev_st.st_mode))
945 die("Expected that %s is a block device", dev);
946 if (stat(".", &cwd_st) < 0)
947 die("Cannot stat cwd: %m");
948 if (cwd_st.st_dev != dev_st.st_rdev)
949 die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
952 .dqb_bhardlimit = block_quota,
953 .dqb_bsoftlimit = block_quota,
954 .dqb_ihardlimit = inode_quota,
955 .dqb_isoftlimit = inode_quota,
956 .dqb_valid = QIF_LIMITS,
958 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
959 die("Cannot set disk quota: %m");
960 msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
965 /*** The keeper process ***/
968 signal_alarm(int unused UNUSED)
970 /* Time limit checks are synchronous, so we only schedule them there. */
976 signal_int(int unused UNUSED)
978 /* Interrupts are fatal, so no synchronization requirements. */
979 meta_printf("exitsig:%d\n", SIGINT);
980 err("SG: Interrupted");
983 #define PROC_BUF_SIZE 4096
985 read_proc_file(char *buf, char *name, int *fdp)
991 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
992 *fdp = open(buf, O_RDONLY);
994 die("open(%s): %m", buf);
996 lseek(*fdp, 0, SEEK_SET);
997 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
998 die("read on /proc/$pid/%s: %m", name);
999 if (c >= PROC_BUF_SIZE-1)
1000 die("/proc/$pid/%s too long", name);
1005 get_wall_time_ms(void)
1007 struct timeval now, wall;
1008 gettimeofday(&now, NULL);
1009 timersub(&now, &start_time, &wall);
1010 return wall.tv_sec*1000 + wall.tv_usec/1000;
1014 get_run_time_ms(struct rusage *rus)
1017 return cg_get_run_time_ms();
1021 struct timeval total;
1022 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
1023 return total.tv_sec*1000 + total.tv_usec/1000;
1026 char buf[PROC_BUF_SIZE], *x;
1028 static int proc_stat_fd;
1030 read_proc_file(buf, "stat", &proc_stat_fd);
1032 while (*x && *x != ' ')
1037 die("proc stat syntax error 1");
1038 while (*x && (*x != ')' || x[1] != ' '))
1040 while (*x == ')' || *x == ' ')
1042 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1043 die("proc stat syntax error 2");
1045 return (utime + stime) * 1000 / ticks_per_sec;
1053 int wall_ms = get_wall_time_ms();
1054 if (wall_ms > wall_timeout)
1055 err("TO: Time limit exceeded (wall clock)");
1057 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1061 int ms = get_run_time_ms(NULL);
1063 fprintf(stderr, "[time check: %d msec]\n", ms);
1064 if (ms > timeout && ms > extra_timeout)
1065 err("TO: Time limit exceeded");
1072 read_errors_from_fd = error_pipes[0];
1073 close(error_pipes[1]);
1075 struct sigaction sa;
1076 bzero(&sa, sizeof(sa));
1077 sa.sa_handler = signal_int;
1078 sigaction(SIGINT, &sa, NULL);
1080 gettimeofday(&start_time, NULL);
1081 ticks_per_sec = sysconf(_SC_CLK_TCK);
1082 if (ticks_per_sec <= 0)
1083 die("Invalid ticks_per_sec!");
1085 if (timeout || wall_timeout)
1087 sa.sa_handler = signal_alarm;
1088 sigaction(SIGALRM, &sa, NULL);
1102 p = wait4(box_pid, &stat, 0, &rus);
1110 die("wait4: unknown pid %d exited!", p);
1113 // Check error pipe if there is an internal error passed from inside the box
1115 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1122 if (WIFEXITED(stat))
1125 if (WEXITSTATUS(stat))
1127 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1128 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1130 if (timeout && total_ms > timeout)
1131 err("TO: Time limit exceeded");
1132 if (wall_timeout && wall_ms > wall_timeout)
1133 err("TO: Time limit exceeded (wall clock)");
1135 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1136 total_ms/1000, total_ms%1000,
1137 wall_ms/1000, wall_ms%1000);
1140 else if (WIFSIGNALED(stat))
1142 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1144 err("SG: Caught fatal signal %d", WTERMSIG(stat));
1146 else if (WIFSTOPPED(stat))
1148 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1150 err("SG: Stopped by signal %d", WSTOPSIG(stat));
1153 die("wait4: unknown status %x, giving up!", stat);
1157 /*** The process running inside the box ***/
1162 if (mkdir("root", 0750) < 0 && errno != EEXIST)
1163 die("mkdir('root'): %m");
1165 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1166 die("Cannot mount root ramdisk: %m");
1170 if (chroot("root") < 0)
1171 die("Chroot failed: %m");
1173 if (chdir("root/box") < 0)
1174 die("Cannot change current directory: %m");
1178 setup_credentials(void)
1180 if (setresgid(box_gid, box_gid, box_gid) < 0)
1181 die("setresgid: %m");
1182 if (setgroups(0, NULL) < 0)
1183 die("setgroups: %m");
1184 if (setresuid(box_uid, box_uid, box_uid) < 0)
1185 die("setresuid: %m");
1195 if (open(redir_stdin, O_RDONLY) != 0)
1196 die("open(\"%s\"): %m", redir_stdin);
1201 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1202 die("open(\"%s\"): %m", redir_stdout);
1207 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1208 die("open(\"%s\"): %m", redir_stderr);
1215 setup_rlim(const char *res_name, int res, rlim_t limit)
1217 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1218 if (setrlimit(res, &rl) < 0)
1219 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1225 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1228 RLIM(AS, memory_limit * 1024);
1230 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1235 RLIM(NPROC, max_processes);
1241 box_inside(void *arg)
1244 write_errors_to_fd = error_pipes[1];
1245 close(error_pipes[0]);
1249 setup_credentials();
1252 char **env = setup_environment();
1254 if (set_cwd && chdir(set_cwd))
1257 execve(args[0], args, env);
1258 die("execve(\"%s\"): %m", args[0]);
1264 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1265 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1266 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1267 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1269 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1271 if (chdir(box_dir) < 0)
1272 die("chdir(%s): %m", box_dir);
1280 msg("Preparing sandbox directory\n");
1282 if (mkdir("box", 0700) < 0)
1283 die("Cannot create box: %m");
1284 if (chown("box", orig_uid, orig_gid) < 0)
1285 die("Cannot chown box: %m");
1296 if (!dir_exists("box"))
1297 die("Box directory not found, there isn't anything to clean up");
1299 msg("Deleting sandbox directory\n");
1307 if (!dir_exists("box"))
1308 die("Box directory not found, did you run `isolate --init'?");
1310 chowntree("box", box_uid, box_gid);
1311 cleanup_ownership = 1;
1313 if (pipe(error_pipes) < 0)
1315 for (int i=0; i<2; i++)
1316 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1317 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1318 die("fcntl on pipe: %m");
1321 box_inside, // Function to execute as the body of the new process
1322 argv, // Pass our stack
1323 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1324 argv); // Pass the arguments
1328 die("clone returned 0");
1335 printf("Process isolator 1.0\n");
1336 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1337 printf("\nCompile-time configuration:\n");
1338 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1339 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1340 CONFIG_ISOLATE_FIRST_UID,
1341 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1342 CONFIG_ISOLATE_FIRST_GID,
1343 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1348 static void __attribute__((format(printf,1,2)))
1349 usage(const char *msg, ...)
1354 va_start(args, msg);
1355 vfprintf(stderr, msg, args);
1359 Usage: isolate [<options>] <command>\n\
1362 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1363 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1364 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1365 --cg-timing\t\tTime limits affects total run time of the control group\n\
1366 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1367 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1368 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1369 --dir=...:<opt>\tSpecify options for a rule:\n\
1370 \t\t\t\tdev\tAllow access to special files\n\
1371 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1372 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1373 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1374 \t\t\t\trw\tAllow read-write access\n\
1375 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1376 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1377 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1378 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1379 -e, --full-env\t\tInherit full environment of the parent process\n\
1380 -m, --mem=<size>\tLimit address space to <size> KB\n\
1381 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1382 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1383 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1384 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1385 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1386 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1387 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1388 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1389 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1390 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1393 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1394 --run -- <cmd> ...\tRun given command within sandbox\n\
1395 --cleanup\t\tClean up sandbox\n\
1396 --version\t\tDisplay program version and configuration\n\
1411 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1413 static const struct option long_opts[] = {
1414 { "box-id", 1, NULL, 'b' },
1415 { "chdir", 1, NULL, 'c' },
1416 { "cg", 0, NULL, OPT_CG },
1417 { "cg-mem", 1, NULL, OPT_CG_MEM },
1418 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1419 { "cleanup", 0, NULL, OPT_CLEANUP },
1420 { "dir", 1, NULL, 'd' },
1421 { "env", 1, NULL, 'E' },
1422 { "extra-time", 1, NULL, 'x' },
1423 { "full-env", 0, NULL, 'e' },
1424 { "init", 0, NULL, OPT_INIT },
1425 { "mem", 1, NULL, 'm' },
1426 { "meta", 1, NULL, 'M' },
1427 { "processes", 2, NULL, 'p' },
1428 { "quota", 1, NULL, 'q' },
1429 { "run", 0, NULL, OPT_RUN },
1430 { "stack", 1, NULL, 'k' },
1431 { "stderr", 1, NULL, 'r' },
1432 { "stdin", 1, NULL, 'i' },
1433 { "stdout", 1, NULL, 'o' },
1434 { "time", 1, NULL, 't' },
1435 { "verbose", 0, NULL, 'v' },
1436 { "version", 0, NULL, OPT_VERSION },
1437 { "wall-time", 1, NULL, 'w' },
1438 { NULL, 0, NULL, 0 }
1442 main(int argc, char **argv)
1446 enum opt_code mode = 0;
1450 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1454 box_id = atoi(optarg);
1463 if (!set_dir_action(optarg))
1464 usage("Invalid directory specified: %s\n", optarg);
1470 if (!set_env_action(optarg))
1471 usage("Invalid environment specified: %s\n", optarg);
1474 stack_limit = atoi(optarg);
1477 redir_stdin = optarg;
1480 memory_limit = atoi(optarg);
1486 redir_stdout = optarg;
1490 max_processes = atoi(optarg);
1495 sep = strchr(optarg, ',');
1497 usage("Invalid quota specified: %s\n", optarg);
1498 block_quota = atoi(optarg);
1499 inode_quota = atoi(sep+1);
1502 redir_stderr = optarg;
1505 timeout = 1000*atof(optarg);
1511 wall_timeout = 1000*atof(optarg);
1514 extra_timeout = 1000*atof(optarg);
1520 if (!mode || mode == c)
1523 usage("Only one command is allowed.\n");
1526 cg_memory_limit = atoi(optarg);
1536 usage("Please specify an isolate command (e.g. --init, --run).\n");
1537 if (mode == OPT_VERSION)
1544 die("Must be started as root");
1545 orig_uid = getuid();
1546 orig_gid = getgid();
1556 usage("--init mode takes no parameters\n");
1561 usage("--run mode requires a command to run\n");
1566 usage("--cleanup mode takes no parameters\n");
1570 die("Internal error: mode mismatch");