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>
29 #include <sys/signal.h>
30 #include <sys/resource.h>
31 #include <sys/mount.h>
33 #include <sys/quota.h>
35 #include <sys/fsuid.h>
37 #define NONRET __attribute__((noreturn))
38 #define UNUSED __attribute__((unused))
39 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
41 static int timeout; /* milliseconds */
42 static int wall_timeout;
43 static int extra_timeout;
44 static int pass_environ;
46 static int memory_limit;
47 static int stack_limit;
48 static int block_quota;
49 static int inode_quota;
50 static int max_processes = 1;
51 static char *redir_stdin, *redir_stdout, *redir_stderr;
55 static int cg_memory_limit;
59 static char box_dir[1024];
64 static uid_t orig_uid;
65 static gid_t orig_gid;
67 static int partial_line;
68 static int cleanup_ownership;
70 static struct timeval start_time;
71 static int ticks_per_sec;
72 static int total_ms, wall_ms;
73 static volatile sig_atomic_t timer_tick;
75 static int error_pipes[2];
76 static int write_errors_to_fd;
77 static int read_errors_from_fd;
79 static void die(char *msg, ...) NONRET;
80 static void cg_stats(void);
81 static int get_wall_time_ms(void);
82 static int get_run_time_ms(struct rusage *rus);
84 static void chowntree(char *path, uid_t uid, gid_t gid);
88 static FILE *metafile;
91 meta_open(const char *name)
93 if (!strcmp(name, "-"))
98 if (setfsuid(getuid()) < 0)
99 die("Failed to switch FS UID: %m");
100 metafile = fopen(name, "w");
101 if (setfsuid(geteuid()) < 0)
102 die("Failed to switch FS UID back: %m");
104 die("Failed to open metafile '%s'",name);
110 if (metafile && metafile != stdout)
114 static void __attribute__((format(printf,1,2)))
115 meta_printf(const char *fmt, ...)
122 vfprintf(metafile, fmt, args);
127 final_stats(struct rusage *rus)
129 total_ms = get_run_time_ms(rus);
130 wall_ms = get_wall_time_ms();
132 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
133 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
134 meta_printf("max-rss:%ld\n", rus->ru_maxrss);
135 meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
136 meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
141 /*** Messages and exits ***/
148 kill(-box_pid, SIGKILL);
149 kill(box_pid, SIGKILL);
150 meta_printf("killed:1\n");
155 p = wait4(box_pid, &stat, 0, &rus);
156 while (p < 0 && errno == EINTR);
158 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
163 if (rc < 2 && cleanup_ownership)
164 chowntree("box", orig_uid, orig_gid);
178 /* Report an error of the sandbox itself */
179 static void NONRET __attribute__((format(printf,1,2)))
185 int n = vsnprintf(buf, sizeof(buf), msg, args);
187 if (write_errors_to_fd)
189 // We are inside the box, have to use error pipe for error reporting.
190 // We hope that the whole error message fits in PIPE_BUF bytes.
191 write(write_errors_to_fd, buf, n);
195 // Otherwise, we in the box keeper process, so we report errors normally
197 meta_printf("status:XX\nmessage:%s\n", buf);
203 /* Report an error of the program inside the sandbox */
204 static void NONRET __attribute__((format(printf,1,2)))
210 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
212 meta_printf("status:%c%c\n", msg[0], msg[1]);
216 vsnprintf(buf, sizeof(buf), msg, args);
217 meta_printf("message:%s\n", buf);
223 /* Write a message, but only if in verbose mode */
224 static void __attribute__((format(printf,1,2)))
231 int len = strlen(msg);
233 partial_line = (msg[len-1] != '\n');
234 vfprintf(stderr, msg, args);
240 /*** Utility functions ***/
245 void *p = malloc(size);
247 die("Out of memory");
254 char *p = strdup(str);
256 die("Out of memory");
260 static int dir_exists(char *path)
263 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
266 static int rmtree_helper(const char *fpath, const struct stat *sb,
267 int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
269 if (S_ISDIR(sb->st_mode))
271 if (rmdir(fpath) < 0)
272 die("Cannot rmdir %s: %m", fpath);
276 if (unlink(fpath) < 0)
277 die("Cannot unlink %s: %m", fpath);
285 nftw(path, rmtree_helper, 32, FTW_MOUNT | FTW_PHYS | FTW_DEPTH);
288 static uid_t chown_uid;
289 static gid_t chown_gid;
291 static int chowntree_helper(const char *fpath, const struct stat *sb UNUSED,
292 int typeflag UNUSED, struct FTW *ftwbuf UNUSED)
294 if (lchown(fpath, chown_uid, chown_gid) < 0)
295 die("Cannot chown %s: %m", fpath);
301 chowntree(char *path, uid_t uid, gid_t gid)
305 nftw(path, chowntree_helper, 32, FTW_MOUNT | FTW_PHYS);
308 /*** Environment rules ***/
311 char *var; // Variable to match
312 char *val; // ""=clear, NULL=inherit
314 struct env_rule *next;
317 static struct env_rule *first_env_rule;
318 static struct env_rule **last_env_rule = &first_env_rule;
320 static struct env_rule default_env_rules[] = {
321 { "LIBC_FATAL_STDERR_", "1" }
325 set_env_action(char *a0)
327 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
328 char *a = (char *)(r+1);
331 char *sep = strchr(a, '=');
343 last_env_rule = &r->next;
349 match_env_var(char *env_entry, struct env_rule *r)
351 if (strncmp(env_entry, r->var, r->var_len))
353 return (env_entry[r->var_len] == '=');
357 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
359 // First remove the variable if already set
361 while (pos < *env_sizep && !match_env_var(env[pos], r))
363 if (pos < *env_sizep)
366 env[pos] = env[*env_sizep];
367 env[*env_sizep] = NULL;
370 // What is the new value?
376 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
377 sprintf(new, "%s=%s", r->var, r->val);
382 while (environ[pos] && !match_env_var(environ[pos], r))
384 if (!(new = environ[pos]))
388 // Add it at the end of the array
389 env[(*env_sizep)++] = new;
390 env[*env_sizep] = NULL;
394 setup_environment(void)
396 // Link built-in rules with user rules
397 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
399 default_env_rules[i].next = first_env_rule;
400 first_env_rule = &default_env_rules[i];
403 // Scan the original environment
404 char **orig_env = environ;
406 while (orig_env[orig_size])
409 // For each rule, reserve one more slot and calculate length
411 for (struct env_rule *r = first_env_rule; r; r=r->next)
414 r->var_len = strlen(r->var);
417 // Create a new environment
418 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
422 memcpy(env, environ, orig_size * sizeof(char *));
429 // Apply the rules one by one
430 for (struct env_rule *r = first_env_rule; r; r=r->next)
431 apply_env_rule(env, &size, r);
433 // Return the new env and pass some gossip
436 fprintf(stderr, "Passing environment:\n");
437 for (int i=0; env[i]; i++)
438 fprintf(stderr, "\t%s\n", env[i]);
443 /*** Directory rules ***/
446 char *inside; // A relative path
447 char *outside; // This can be an absolute path or a relative path starting with "./"
448 unsigned int flags; // DIR_FLAG_xxx
449 struct dir_rule *next;
452 enum dir_rule_flags {
460 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
462 static struct dir_rule *first_dir_rule;
463 static struct dir_rule **last_dir_rule = &first_dir_rule;
465 static int add_dir_rule(char *in, char *out, unsigned int flags)
467 // Make sure that "in" is relative
474 if (flags & DIR_FLAG_FS)
476 if (!out || out[0] == '/')
481 if (out && out[0] != '/' && strncmp(out, "./", 2))
485 // Override an existing rule
487 for (r = first_dir_rule; r; r = r->next)
488 if (!strcmp(r->inside, in))
494 r = xmalloc(sizeof(*r));
497 last_dir_rule = &r->next;
505 static unsigned int parse_dir_option(char *opt)
507 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
508 if (!strcmp(opt, dir_flag_names[i]))
510 die("Unknown directory option %s", opt);
513 static int set_dir_action(char *arg)
517 char *colon = strchr(arg, ':');
518 unsigned int flags = 0;
522 char *next = strchr(colon, ':');
525 flags |= parse_dir_option(colon);
529 char *eq = strchr(arg, '=');
533 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
537 char *out = xmalloc(1 + strlen(arg) + 1);
538 sprintf(out, "/%s", arg);
539 return add_dir_rule(arg, out, flags);
543 static void init_dir_rules(void)
545 set_dir_action("box=./box:rw");
546 set_dir_action("bin");
547 set_dir_action("dev:dev");
548 set_dir_action("lib");
549 set_dir_action("lib64:maybe");
550 set_dir_action("proc=proc:fs");
551 set_dir_action("usr");
554 static void make_dir(char *path)
556 char *sep = (path[0] == '/' ? path+1 : path);
560 sep = strchr(sep, '/');
564 if (!dir_exists(path) && mkdir(path, 0777) < 0)
565 die("Cannot create directory %s: %m\n", path);
573 static void apply_dir_rules(void)
575 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
577 char *in = r->inside;
578 char *out = r->outside;
581 msg("Not binding anything on %s\n", r->inside);
585 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
587 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
592 snprintf(root_in, sizeof(root_in), "root/%s", in);
595 unsigned long mount_flags = 0;
596 if (!(r->flags & DIR_FLAG_RW))
597 mount_flags |= MS_RDONLY;
598 if (r->flags & DIR_FLAG_NOEXEC)
599 mount_flags |= MS_NOEXEC;
600 if (!(r->flags & DIR_FLAG_DEV))
601 mount_flags |= MS_NODEV;
603 if (r->flags & DIR_FLAG_FS)
605 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
606 if (mount("none", root_in, out, mount_flags, "") < 0)
607 die("Cannot mount %s on %s: %m", out, in);
611 mount_flags |= MS_BIND | MS_NOSUID;
612 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
613 // Most mount flags need remount to work
614 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
615 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
616 die("Cannot mount %s on %s: %m", out, in);
621 /*** Control groups ***/
623 struct cg_controller_desc {
635 static const struct cg_controller_desc cg_controllers[CG_NUM_CONTROLLERS+1] = {
636 [CG_MEMORY] = { "memory", 0 },
637 [CG_CPUACCT] = { "cpuacct", 0 },
638 [CG_CPUSET] = { "cpuset", 1 },
639 [CG_NUM_CONTROLLERS] = { NULL, 0 },
642 #define FOREACH_CG_CONTROLLER(_controller) \
643 for (cg_controller (_controller) = 0; \
644 (_controller) < CG_NUM_CONTROLLERS; (_controller)++)
646 static const char *cg_controller_name(cg_controller c)
648 return cg_controllers[c].name;
651 static int cg_controller_optional(cg_controller c)
653 return cg_controllers[c].optional;
656 static char cg_name[256];
658 #define CG_BUFSIZE 1024
661 cg_makepath(char *buf, size_t len, cg_controller c, const char *attr)
663 const char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
664 snprintf(buf, len, "%s/%s/%s/%s", cg_root, cg_controller_name(c), cg_name, attr);
668 cg_read(cg_controller controller, const char *attr, char *buf)
678 cg_makepath(path, sizeof(path), controller, attr);
680 int fd = open(path, O_RDONLY);
685 die("Cannot read %s: %m", path);
688 int n = read(fd, buf, CG_BUFSIZE);
693 die("Cannot read %s: %m", path);
695 if (n >= CG_BUFSIZE - 1)
696 die("Attribute %s too long", path);
697 if (n > 0 && buf[n-1] == '\n')
702 msg("CG: Read %s = %s\n", attr, buf);
708 static void __attribute__((format(printf,3,4)))
709 cg_write(cg_controller controller, const char *attr, const char *fmt, ...)
721 char buf[CG_BUFSIZE];
722 int n = vsnprintf(buf, sizeof(buf), fmt, args);
724 die("cg_write: Value for attribute %s is too long", attr);
727 msg("CG: Write %s = %s", attr, buf);
730 cg_makepath(path, sizeof(path), controller, attr);
732 int fd = open(path, O_WRONLY | O_TRUNC);
738 die("Cannot write %s: %m", path);
741 int written = write(fd, buf, n);
747 die("Cannot set %s to %s: %m", path, buf);
750 die("Short write to %s (%d out of %d bytes)", path, written, n);
762 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
763 if (!dir_exists(cg_root))
764 die("Control group filesystem at %s not mounted", cg_root);
766 snprintf(cg_name, sizeof(cg_name), "box-%d", box_id);
767 msg("Using control group %s\n", cg_name);
777 char buf[CG_BUFSIZE];
780 FOREACH_CG_CONTROLLER(controller)
782 cg_makepath(path, sizeof(path), controller, "");
783 if (stat(path, &st) >= 0 || errno != ENOENT)
785 msg("Control group %s already exists, trying to empty it.\n", path);
787 die("Failed to reset control group %s: %m", path);
790 if (mkdir(path, 0777) < 0 && !cg_controller_optional(controller))
791 die("Failed to create control group %s: %m", path);
794 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
795 if (cg_read(CG_CPUSET, "?cpuset.cpus", buf))
796 cg_write(CG_CPUSET, "cpuset.cpus", "%s", buf);
797 if (cg_read(CG_CPUSET, "?cpuset.mems", buf))
798 cg_write(CG_CPUSET, "cpuset.mems", "%s", buf);
807 msg("Entering control group %s\n", cg_name);
809 FOREACH_CG_CONTROLLER(controller)
811 if (cg_controller_optional(controller))
812 cg_write(controller, "?tasks", "%d\n", (int) getpid());
814 cg_write(controller, "tasks", "%d\n", (int) getpid());
819 cg_write(CG_MEMORY, "memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
820 cg_write(CG_MEMORY, "?memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
824 cg_write(CG_CPUACCT, "cpuacct.usage", "0\n");
828 cg_get_run_time_ms(void)
833 char buf[CG_BUFSIZE];
834 cg_read(CG_CPUACCT, "cpuacct.usage", buf);
835 unsigned long long ns = atoll(buf);
845 char buf[CG_BUFSIZE];
847 // Memory usage statistics
848 unsigned long long mem=0, memsw=0;
849 if (cg_read(CG_MEMORY, "?memory.max_usage_in_bytes", buf))
851 if (cg_read(CG_MEMORY, "?memory.memsw.max_usage_in_bytes", buf))
858 meta_printf("cg-mem:%lld\n", mem >> 10);
864 char buf[CG_BUFSIZE];
869 FOREACH_CG_CONTROLLER(controller)
871 if (cg_controller_optional(controller))
873 if (!cg_read(controller, "?tasks", buf))
877 cg_read(controller, "tasks", buf);
880 die("Some tasks left in controller %s of cgroup %s, failed to remove it",
881 cg_controller_name(controller), cg_name);
884 cg_makepath(path, sizeof(path), controller, "");
887 die("Cannot remove control group %s: %m", path);
891 /*** Disk quotas ***/
894 path_begins_with(char *path, char *with)
897 if (*path++ != *with++)
899 return (!*with || *with == '/');
903 find_device(char *path)
905 FILE *f = setmntent("/proc/mounts", "r");
907 die("Cannot open /proc/mounts: %m");
911 char *best_dev = NULL;
912 while (me = getmntent(f))
914 if (!path_begins_with(me->mnt_fsname, "/dev"))
916 if (path_begins_with(path, me->mnt_dir))
918 int len = strlen(me->mnt_dir);
923 best_dev = xstrdup(me->mnt_fsname);
938 if (!getcwd(cwd, sizeof(cwd)))
941 char *dev = find_device(cwd);
943 die("Cannot identify filesystem which contains %s", cwd);
944 msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
947 struct stat dev_st, cwd_st;
948 if (stat(dev, &dev_st) < 0)
949 die("Cannot identify block device %s: %m", dev);
950 if (!S_ISBLK(dev_st.st_mode))
951 die("Expected that %s is a block device", dev);
952 if (stat(".", &cwd_st) < 0)
953 die("Cannot stat cwd: %m");
954 if (cwd_st.st_dev != dev_st.st_rdev)
955 die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
958 .dqb_bhardlimit = block_quota,
959 .dqb_bsoftlimit = block_quota,
960 .dqb_ihardlimit = inode_quota,
961 .dqb_isoftlimit = inode_quota,
962 .dqb_valid = QIF_LIMITS,
964 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
965 die("Cannot set disk quota: %m");
966 msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
971 /*** The keeper process ***/
974 signal_alarm(int unused UNUSED)
976 /* Time limit checks are synchronous, so we only schedule them there. */
982 signal_int(int unused UNUSED)
984 /* Interrupts are fatal, so no synchronization requirements. */
985 meta_printf("exitsig:%d\n", SIGINT);
986 err("SG: Interrupted");
989 #define PROC_BUF_SIZE 4096
991 read_proc_file(char *buf, char *name, int *fdp)
997 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
998 *fdp = open(buf, O_RDONLY);
1000 die("open(%s): %m", buf);
1002 lseek(*fdp, 0, SEEK_SET);
1003 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
1004 die("read on /proc/$pid/%s: %m", name);
1005 if (c >= PROC_BUF_SIZE-1)
1006 die("/proc/$pid/%s too long", name);
1011 get_wall_time_ms(void)
1013 struct timeval now, wall;
1014 gettimeofday(&now, NULL);
1015 timersub(&now, &start_time, &wall);
1016 return wall.tv_sec*1000 + wall.tv_usec/1000;
1020 get_run_time_ms(struct rusage *rus)
1023 return cg_get_run_time_ms();
1027 struct timeval total;
1028 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
1029 return total.tv_sec*1000 + total.tv_usec/1000;
1032 char buf[PROC_BUF_SIZE], *x;
1034 static int proc_stat_fd;
1036 read_proc_file(buf, "stat", &proc_stat_fd);
1038 while (*x && *x != ' ')
1043 die("proc stat syntax error 1");
1044 while (*x && (*x != ')' || x[1] != ' '))
1046 while (*x == ')' || *x == ' ')
1048 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
1049 die("proc stat syntax error 2");
1051 return (utime + stime) * 1000 / ticks_per_sec;
1059 int wall_ms = get_wall_time_ms();
1060 if (wall_ms > wall_timeout)
1061 err("TO: Time limit exceeded (wall clock)");
1063 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
1067 int ms = get_run_time_ms(NULL);
1069 fprintf(stderr, "[time check: %d msec]\n", ms);
1070 if (ms > timeout && ms > extra_timeout)
1071 err("TO: Time limit exceeded");
1078 read_errors_from_fd = error_pipes[0];
1079 close(error_pipes[1]);
1081 struct sigaction sa;
1082 bzero(&sa, sizeof(sa));
1083 sa.sa_handler = signal_int;
1084 sigaction(SIGINT, &sa, NULL);
1086 gettimeofday(&start_time, NULL);
1087 ticks_per_sec = sysconf(_SC_CLK_TCK);
1088 if (ticks_per_sec <= 0)
1089 die("Invalid ticks_per_sec!");
1091 if (timeout || wall_timeout)
1093 sa.sa_handler = signal_alarm;
1094 sigaction(SIGALRM, &sa, NULL);
1108 p = wait4(box_pid, &stat, 0, &rus);
1116 die("wait4: unknown pid %d exited!", p);
1119 // Check error pipe if there is an internal error passed from inside the box
1121 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1128 if (WIFEXITED(stat))
1131 if (WEXITSTATUS(stat))
1133 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1134 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1136 if (timeout && total_ms > timeout)
1137 err("TO: Time limit exceeded");
1138 if (wall_timeout && wall_ms > wall_timeout)
1139 err("TO: Time limit exceeded (wall clock)");
1141 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1142 total_ms/1000, total_ms%1000,
1143 wall_ms/1000, wall_ms%1000);
1146 else if (WIFSIGNALED(stat))
1148 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1150 err("SG: Caught fatal signal %d", WTERMSIG(stat));
1152 else if (WIFSTOPPED(stat))
1154 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1156 err("SG: Stopped by signal %d", WSTOPSIG(stat));
1159 die("wait4: unknown status %x, giving up!", stat);
1163 /*** The process running inside the box ***/
1168 if (mkdir("root", 0750) < 0 && errno != EEXIST)
1169 die("mkdir('root'): %m");
1171 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1172 die("Cannot mount root ramdisk: %m");
1176 if (chroot("root") < 0)
1177 die("Chroot failed: %m");
1179 if (chdir("root/box") < 0)
1180 die("Cannot change current directory: %m");
1184 setup_credentials(void)
1186 if (setresgid(box_gid, box_gid, box_gid) < 0)
1187 die("setresgid: %m");
1188 if (setgroups(0, NULL) < 0)
1189 die("setgroups: %m");
1190 if (setresuid(box_uid, box_uid, box_uid) < 0)
1191 die("setresuid: %m");
1201 if (open(redir_stdin, O_RDONLY) != 0)
1202 die("open(\"%s\"): %m", redir_stdin);
1207 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1208 die("open(\"%s\"): %m", redir_stdout);
1213 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1214 die("open(\"%s\"): %m", redir_stderr);
1221 setup_rlim(const char *res_name, int res, rlim_t limit)
1223 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1224 if (setrlimit(res, &rl) < 0)
1225 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1231 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1234 RLIM(AS, (rlim_t)memory_limit * 1024);
1236 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1241 RLIM(NPROC, max_processes);
1247 box_inside(void *arg)
1250 write_errors_to_fd = error_pipes[1];
1251 close(error_pipes[0]);
1256 setup_credentials();
1259 char **env = setup_environment();
1261 if (set_cwd && chdir(set_cwd))
1264 execve(args[0], args, env);
1265 die("execve(\"%s\"): %m", args[0]);
1271 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1272 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1273 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1274 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1276 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1278 if (chdir(box_dir) < 0)
1279 die("chdir(%s): %m", box_dir);
1287 msg("Preparing sandbox directory\n");
1289 if (mkdir("box", 0700) < 0)
1290 die("Cannot create box: %m");
1291 if (chown("box", orig_uid, orig_gid) < 0)
1292 die("Cannot chown box: %m");
1303 if (!dir_exists("box"))
1304 die("Box directory not found, there isn't anything to clean up");
1306 msg("Deleting sandbox directory\n");
1314 if (!dir_exists("box"))
1315 die("Box directory not found, did you run `isolate --init'?");
1317 chowntree("box", box_uid, box_gid);
1318 cleanup_ownership = 1;
1320 if (pipe(error_pipes) < 0)
1322 for (int i=0; i<2; i++)
1323 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1324 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1325 die("fcntl on pipe: %m");
1328 box_inside, // Function to execute as the body of the new process
1329 argv, // Pass our stack
1330 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1331 argv); // Pass the arguments
1335 die("clone returned 0");
1342 printf("Process isolator 1.0\n");
1343 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1344 printf("\nCompile-time configuration:\n");
1345 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1346 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1347 CONFIG_ISOLATE_FIRST_UID,
1348 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1349 CONFIG_ISOLATE_FIRST_GID,
1350 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1355 static void __attribute__((format(printf,1,2)))
1356 usage(const char *msg, ...)
1361 va_start(args, msg);
1362 vfprintf(stderr, msg, args);
1366 Usage: isolate [<options>] <command>\n\
1369 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1370 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1371 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1372 --cg-timing\t\tTime limits affects total run time of the control group\n\
1373 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1374 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1375 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1376 --dir=...:<opt>\tSpecify options for a rule:\n\
1377 \t\t\t\tdev\tAllow access to special files\n\
1378 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1379 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1380 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1381 \t\t\t\trw\tAllow read-write access\n\
1382 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1383 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1384 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1385 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1386 -e, --full-env\t\tInherit full environment of the parent process\n\
1387 -m, --mem=<size>\tLimit address space to <size> KB\n\
1388 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1389 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1390 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1391 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1392 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1393 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1394 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1395 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1396 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1397 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1400 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1401 --run -- <cmd> ...\tRun given command within sandbox\n\
1402 --cleanup\t\tClean up sandbox\n\
1403 --version\t\tDisplay program version and configuration\n\
1418 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1420 static const struct option long_opts[] = {
1421 { "box-id", 1, NULL, 'b' },
1422 { "chdir", 1, NULL, 'c' },
1423 { "cg", 0, NULL, OPT_CG },
1424 { "cg-mem", 1, NULL, OPT_CG_MEM },
1425 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1426 { "cleanup", 0, NULL, OPT_CLEANUP },
1427 { "dir", 1, NULL, 'd' },
1428 { "env", 1, NULL, 'E' },
1429 { "extra-time", 1, NULL, 'x' },
1430 { "full-env", 0, NULL, 'e' },
1431 { "init", 0, NULL, OPT_INIT },
1432 { "mem", 1, NULL, 'm' },
1433 { "meta", 1, NULL, 'M' },
1434 { "processes", 2, NULL, 'p' },
1435 { "quota", 1, NULL, 'q' },
1436 { "run", 0, NULL, OPT_RUN },
1437 { "stack", 1, NULL, 'k' },
1438 { "stderr", 1, NULL, 'r' },
1439 { "stdin", 1, NULL, 'i' },
1440 { "stdout", 1, NULL, 'o' },
1441 { "time", 1, NULL, 't' },
1442 { "verbose", 0, NULL, 'v' },
1443 { "version", 0, NULL, OPT_VERSION },
1444 { "wall-time", 1, NULL, 'w' },
1445 { NULL, 0, NULL, 0 }
1449 main(int argc, char **argv)
1453 enum opt_code mode = 0;
1457 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1461 box_id = atoi(optarg);
1470 if (!set_dir_action(optarg))
1471 usage("Invalid directory specified: %s\n", optarg);
1477 if (!set_env_action(optarg))
1478 usage("Invalid environment specified: %s\n", optarg);
1481 stack_limit = atoi(optarg);
1484 redir_stdin = optarg;
1487 memory_limit = atoi(optarg);
1493 redir_stdout = optarg;
1497 max_processes = atoi(optarg);
1502 sep = strchr(optarg, ',');
1504 usage("Invalid quota specified: %s\n", optarg);
1505 block_quota = atoi(optarg);
1506 inode_quota = atoi(sep+1);
1509 redir_stderr = optarg;
1512 timeout = 1000*atof(optarg);
1518 wall_timeout = 1000*atof(optarg);
1521 extra_timeout = 1000*atof(optarg);
1527 if (!mode || (int) mode == c)
1530 usage("Only one command is allowed.\n");
1533 cg_memory_limit = atoi(optarg);
1543 usage("Please specify an isolate command (e.g. --init, --run).\n");
1544 if (mode == OPT_VERSION)
1551 die("Must be started as root");
1552 orig_uid = getuid();
1553 orig_gid = getgid();
1563 usage("--init mode takes no parameters\n");
1568 usage("--run mode requires a command to run\n");
1573 usage("--cleanup mode takes no parameters\n");
1577 die("Internal error: mode mismatch");