2 * A Process Isolator based on Linux Containers
4 * (c) 2012 Martin Mares <mj@ucw.cz>
5 * (c) 2012 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;
52 static int cg_memory_limit;
56 static char box_dir[1024];
61 static uid_t orig_uid;
62 static gid_t orig_gid;
64 static int partial_line;
65 static char cleanup_cmd[256];
67 static struct timeval start_time;
68 static int ticks_per_sec;
69 static int total_ms, wall_ms;
70 static volatile sig_atomic_t timer_tick;
72 static int error_pipes[2];
73 static int write_errors_to_fd;
74 static int read_errors_from_fd;
76 static void die(char *msg, ...) NONRET;
77 static void cg_stats(void);
78 static int get_wall_time_ms(void);
79 static int get_run_time_ms(struct rusage *rus);
83 static FILE *metafile;
86 meta_open(const char *name)
88 if (!strcmp(name, "-"))
93 metafile = fopen(name, "w");
95 die("Failed to open metafile '%s'",name);
101 if (metafile && metafile != stdout)
105 static void __attribute__((format(printf,1,2)))
106 meta_printf(const char *fmt, ...)
113 vfprintf(metafile, fmt, args);
118 final_stats(struct rusage *rus)
120 total_ms = get_run_time_ms(rus);
121 wall_ms = get_wall_time_ms();
123 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
124 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
125 meta_printf("max-rss:%ld\n", rus->ru_maxrss);
126 meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
127 meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
132 /*** Messages and exits ***/
135 xsystem(const char *cmd)
137 int ret = system(cmd);
139 die("system(\"%s\"): %m", cmd);
140 if (!WIFEXITED(ret) || WEXITSTATUS(ret))
141 die("system(\"%s\"): Exited with status %d", cmd, ret);
149 kill(-box_pid, SIGKILL);
150 kill(box_pid, SIGKILL);
151 meta_printf("killed:1\n");
156 p = wait4(box_pid, &stat, 0, &rus);
157 while (p < 0 && errno == EINTR);
159 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
164 if (rc < 2 && cleanup_cmd[0])
165 xsystem(cleanup_cmd);
179 /* Report an error of the sandbox itself */
180 static void NONRET __attribute__((format(printf,1,2)))
186 int n = vsnprintf(buf, sizeof(buf), msg, args);
188 if (write_errors_to_fd)
190 // We are inside the box, have to use error pipe for error reporting.
191 // We hope that the whole error message fits in PIPE_BUF bytes.
192 write(write_errors_to_fd, buf, n);
196 // Otherwise, we in the box keeper process, so we report errors normally
198 meta_printf("status:XX\nmessage:%s\n", buf);
204 /* Report an error of the program inside the sandbox */
205 static void NONRET __attribute__((format(printf,1,2)))
211 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
213 meta_printf("status:%c%c\n", msg[0], msg[1]);
217 vsnprintf(buf, sizeof(buf), msg, args);
218 meta_printf("message:%s\n", buf);
224 /* Write a message, but only if in verbose mode */
225 static void __attribute__((format(printf,1,2)))
232 int len = strlen(msg);
234 partial_line = (msg[len-1] != '\n');
235 vfprintf(stderr, msg, args);
241 /*** Utility functions ***/
246 void *p = malloc(size);
248 die("Out of memory");
255 char *p = strdup(str);
257 die("Out of memory");
261 static int dir_exists(char *path)
264 return (stat(path, &st) >= 0 && S_ISDIR(st.st_mode));
267 /*** Environment rules ***/
270 char *var; // Variable to match
271 char *val; // ""=clear, NULL=inherit
273 struct env_rule *next;
276 static struct env_rule *first_env_rule;
277 static struct env_rule **last_env_rule = &first_env_rule;
279 static struct env_rule default_env_rules[] = {
280 { "LIBC_FATAL_STDERR_", "1" }
284 set_env_action(char *a0)
286 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
287 char *a = (char *)(r+1);
290 char *sep = strchr(a, '=');
302 last_env_rule = &r->next;
308 match_env_var(char *env_entry, struct env_rule *r)
310 if (strncmp(env_entry, r->var, r->var_len))
312 return (env_entry[r->var_len] == '=');
316 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
318 // First remove the variable if already set
320 while (pos < *env_sizep && !match_env_var(env[pos], r))
322 if (pos < *env_sizep)
325 env[pos] = env[*env_sizep];
326 env[*env_sizep] = NULL;
329 // What is the new value?
335 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
336 sprintf(new, "%s=%s", r->var, r->val);
341 while (environ[pos] && !match_env_var(environ[pos], r))
343 if (!(new = environ[pos]))
347 // Add it at the end of the array
348 env[(*env_sizep)++] = new;
349 env[*env_sizep] = NULL;
353 setup_environment(void)
355 // Link built-in rules with user rules
356 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
358 default_env_rules[i].next = first_env_rule;
359 first_env_rule = &default_env_rules[i];
362 // Scan the original environment
363 char **orig_env = environ;
365 while (orig_env[orig_size])
368 // For each rule, reserve one more slot and calculate length
370 for (struct env_rule *r = first_env_rule; r; r=r->next)
373 r->var_len = strlen(r->var);
376 // Create a new environment
377 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
381 memcpy(env, environ, orig_size * sizeof(char *));
388 // Apply the rules one by one
389 for (struct env_rule *r = first_env_rule; r; r=r->next)
390 apply_env_rule(env, &size, r);
392 // Return the new env and pass some gossip
395 fprintf(stderr, "Passing environment:\n");
396 for (int i=0; env[i]; i++)
397 fprintf(stderr, "\t%s\n", env[i]);
402 /*** Directory rules ***/
405 char *inside; // A relative path
406 char *outside; // This can be an absolute path or a relative path starting with "./"
407 unsigned int flags; // DIR_FLAG_xxx
408 struct dir_rule *next;
411 enum dir_rule_flags {
419 static const char * const dir_flag_names[] = { "rw", "noexec", "fs", "maybe", "dev" };
421 static struct dir_rule *first_dir_rule;
422 static struct dir_rule **last_dir_rule = &first_dir_rule;
424 static int add_dir_rule(char *in, char *out, unsigned int flags)
426 // Make sure that "in" is relative
433 if (flags & DIR_FLAG_FS)
435 if (!out || out[0] == '/')
440 if (out && out[0] != '/' && strncmp(out, "./", 2))
444 // Override an existing rule
446 for (r = first_dir_rule; r; r = r->next)
447 if (!strcmp(r->inside, in))
453 r = xmalloc(sizeof(*r));
456 last_dir_rule = &r->next;
464 static unsigned int parse_dir_option(char *opt)
466 for (unsigned int i = 0; i < ARRAY_SIZE(dir_flag_names); i++)
467 if (!strcmp(opt, dir_flag_names[i]))
469 die("Unknown directory option %s", opt);
472 static int set_dir_action(char *arg)
476 char *colon = strchr(arg, ':');
477 unsigned int flags = 0;
481 char *next = strchr(colon, ':');
484 flags |= parse_dir_option(colon);
488 char *eq = strchr(arg, '=');
492 return add_dir_rule(arg, (*eq ? eq : NULL), flags);
496 char *out = xmalloc(1 + strlen(arg) + 1);
497 sprintf(out, "/%s", arg);
498 return add_dir_rule(arg, out, flags);
502 static void init_dir_rules(void)
504 set_dir_action("box=./box:rw");
505 set_dir_action("bin");
506 set_dir_action("dev:dev");
507 set_dir_action("lib");
508 set_dir_action("lib64:maybe");
509 set_dir_action("proc=proc:fs");
510 set_dir_action("usr");
513 static void make_dir(char *path)
515 char *sep = (path[0] == '/' ? path+1 : path);
519 sep = strchr(sep, '/');
523 if (!dir_exists(path) && mkdir(path, 0777) < 0)
524 die("Cannot create directory %s: %m\n", path);
532 static void apply_dir_rules(void)
534 for (struct dir_rule *r = first_dir_rule; r; r=r->next)
536 char *in = r->inside;
537 char *out = r->outside;
540 msg("Not binding anything on %s\n", r->inside);
544 if ((r->flags & DIR_FLAG_MAYBE) && !dir_exists(out))
546 msg("Not binding %s on %s (does not exist)\n", out, r->inside);
551 snprintf(root_in, sizeof(root_in), "root/%s", in);
554 unsigned long mount_flags = 0;
555 if (!(r->flags & DIR_FLAG_RW))
556 mount_flags |= MS_RDONLY;
557 if (r->flags & DIR_FLAG_NOEXEC)
558 mount_flags |= MS_NOEXEC;
559 if (!(r->flags & DIR_FLAG_DEV))
560 mount_flags |= MS_NODEV;
562 if (r->flags & DIR_FLAG_FS)
564 msg("Mounting %s on %s (flags %lx)\n", out, in, mount_flags);
565 if (mount("none", root_in, out, mount_flags, "") < 0)
566 die("Cannot mount %s on %s: %m", out, in);
570 mount_flags |= MS_BIND | MS_NOSUID;
571 msg("Binding %s on %s (flags %lx)\n", out, in, mount_flags);
572 // Most mount flags need remount to work
573 if (mount(out, root_in, "none", mount_flags, "") < 0 ||
574 mount(out, root_in, "none", MS_REMOUNT | mount_flags, "") < 0)
575 die("Cannot mount %s on %s: %m", out, in);
580 /*** Control groups ***/
582 static char cg_path[256];
584 #define CG_BUFSIZE 1024
587 cg_read(char *attr, char *buf)
597 snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
599 int fd = open(path, O_RDONLY);
604 die("Cannot read %s: %m", path);
607 int n = read(fd, buf, CG_BUFSIZE);
609 die("Cannot read %s: %m", path);
610 if (n >= CG_BUFSIZE - 1)
611 die("Attribute %s too long", path);
612 if (n > 0 && buf[n-1] == '\n')
617 msg("CG: Read %s = %s\n", attr, buf);
623 static void __attribute__((format(printf,2,3)))
624 cg_write(char *attr, char *fmt, ...)
629 char buf[CG_BUFSIZE];
630 int n = vsnprintf(buf, sizeof(buf), fmt, args);
632 die("cg_writef: Value for attribute %s is too long", attr);
635 msg("CG: Write %s = %s", attr, buf);
638 snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
640 int fd = open(path, O_WRONLY | O_TRUNC);
642 die("Cannot write %s: %m", path);
644 int written = write(fd, buf, n);
646 die("Cannot set %s to %s: %m", path, buf);
648 die("Short write to %s (%d out of %d bytes)", path, written, n);
660 char *cg_root = CONFIG_ISOLATE_CGROUP_ROOT;
661 if (!dir_exists(cg_root))
662 die("Control group filesystem at %s not mounted", cg_root);
664 snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, box_id);
665 msg("Using control group %s\n", cg_path);
675 char buf[CG_BUFSIZE];
677 if (stat(cg_path, &st) >= 0 || errno != ENOENT)
679 msg("Control group %s already exists, trying to empty it.\n", cg_path);
680 if (rmdir(cg_path) < 0)
681 die("Failed to reset control group %s: %m", cg_path);
684 if (mkdir(cg_path, 0777) < 0)
685 die("Failed to create control group %s: %m", cg_path);
687 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
688 if (cg_read("?../cpuset.cpus", buf))
689 cg_write("cpuset.cpus", "%s", buf);
690 if (cg_read("?../cpuset.mems", buf))
691 cg_write("cpuset.mems", "%s", buf);
700 msg("Entering control group %s\n", cg_path);
703 if (stat(cg_path, &st) < 0)
704 die("Control group %s does not exist: %m", cg_path);
708 cg_write("memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
709 cg_write("memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
713 cg_write("cpuacct.usage", "0\n");
715 cg_write("tasks", "%d\n", (int) getpid());
719 cg_get_run_time_ms(void)
724 char buf[CG_BUFSIZE];
725 cg_read("cpuacct.usage", buf);
726 unsigned long long ns = atoll(buf);
736 char buf[CG_BUFSIZE];
738 // Memory usage statistics
739 unsigned long long mem=0, memsw=0;
740 if (cg_read("?memory.max_usage_in_bytes", buf))
742 if (cg_read("?memory.memsw.max_usage_in_bytes", buf))
749 meta_printf("cg-mem:%lld\n", mem >> 10);
755 char buf[CG_BUFSIZE];
760 cg_read("tasks", buf);
762 die("Some tasks left in control group %s, failed to remove it", cg_path);
764 if (rmdir(cg_path) < 0)
765 die("Cannot remove control group %s: %m", cg_path);
768 /*** Disk quotas ***/
771 path_begins_with(char *path, char *with)
774 if (*path++ != *with++)
776 return (!*with || *with == '/');
780 find_device(char *path)
782 FILE *f = setmntent("/proc/mounts", "r");
784 die("Cannot open /proc/mounts: %m");
788 char *best_dev = NULL;
789 while (me = getmntent(f))
791 if (!path_begins_with(me->mnt_fsname, "/dev"))
793 if (path_begins_with(path, me->mnt_dir))
795 int len = strlen(me->mnt_dir);
800 best_dev = xstrdup(me->mnt_fsname);
815 if (!getcwd(cwd, sizeof(cwd)))
818 char *dev = find_device(cwd);
820 die("Cannot identify filesystem which contains %s", cwd);
821 msg("Quota: Mapped path %s to a filesystem on %s\n", cwd, dev);
824 struct stat dev_st, cwd_st;
825 if (stat(dev, &dev_st) < 0)
826 die("Cannot identify block device %s: %m", dev);
827 if (!S_ISBLK(dev_st.st_mode))
828 die("Expected that %s is a block device", dev);
829 if (stat(".", &cwd_st) < 0)
830 die("Cannot stat cwd: %m");
831 if (cwd_st.st_dev != dev_st.st_rdev)
832 die("Identified %s as a filesystem on %s, but it is obviously false", cwd, dev);
835 .dqb_bhardlimit = block_quota,
836 .dqb_bsoftlimit = block_quota,
837 .dqb_ihardlimit = inode_quota,
838 .dqb_isoftlimit = inode_quota,
839 .dqb_valid = QIF_LIMITS,
841 if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), dev, box_uid, (caddr_t) &dq) < 0)
842 die("Cannot set disk quota: %m");
843 msg("Quota: Set block quota %d and inode quota %d\n", block_quota, inode_quota);
848 /*** The keeper process ***/
851 signal_alarm(int unused UNUSED)
853 /* Time limit checks are synchronous, so we only schedule them there. */
859 signal_int(int unused UNUSED)
861 /* Interrupts are fatal, so no synchronization requirements. */
862 meta_printf("exitsig:%d\n", SIGINT);
863 err("SG: Interrupted");
866 #define PROC_BUF_SIZE 4096
868 read_proc_file(char *buf, char *name, int *fdp)
874 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
875 *fdp = open(buf, O_RDONLY);
877 die("open(%s): %m", buf);
879 lseek(*fdp, 0, SEEK_SET);
880 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
881 die("read on /proc/$pid/%s: %m", name);
882 if (c >= PROC_BUF_SIZE-1)
883 die("/proc/$pid/%s too long", name);
888 get_wall_time_ms(void)
890 struct timeval now, wall;
891 gettimeofday(&now, NULL);
892 timersub(&now, &start_time, &wall);
893 return wall.tv_sec*1000 + wall.tv_usec/1000;
897 get_run_time_ms(struct rusage *rus)
900 return cg_get_run_time_ms();
904 struct timeval total;
905 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
906 return total.tv_sec*1000 + total.tv_usec/1000;
909 char buf[PROC_BUF_SIZE], *x;
911 static int proc_stat_fd;
913 read_proc_file(buf, "stat", &proc_stat_fd);
915 while (*x && *x != ' ')
920 die("proc stat syntax error 1");
921 while (*x && (*x != ')' || x[1] != ' '))
923 while (*x == ')' || *x == ' ')
925 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
926 die("proc stat syntax error 2");
928 return (utime + stime) * 1000 / ticks_per_sec;
936 int wall_ms = get_wall_time_ms();
937 if (wall_ms > wall_timeout)
938 err("TO: Time limit exceeded (wall clock)");
940 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
944 int ms = get_run_time_ms(NULL);
946 fprintf(stderr, "[time check: %d msec]\n", ms);
947 if (ms > timeout && ms > extra_timeout)
948 err("TO: Time limit exceeded");
955 read_errors_from_fd = error_pipes[0];
956 close(error_pipes[1]);
959 bzero(&sa, sizeof(sa));
960 sa.sa_handler = signal_int;
961 sigaction(SIGINT, &sa, NULL);
963 gettimeofday(&start_time, NULL);
964 ticks_per_sec = sysconf(_SC_CLK_TCK);
965 if (ticks_per_sec <= 0)
966 die("Invalid ticks_per_sec!");
968 if (timeout || wall_timeout)
970 sa.sa_handler = signal_alarm;
971 sigaction(SIGALRM, &sa, NULL);
985 p = wait4(box_pid, &stat, 0, &rus);
993 die("wait4: unknown pid %d exited!", p);
996 // Check error pipe if there is an internal error passed from inside the box
998 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
1005 if (WIFEXITED(stat))
1008 if (WEXITSTATUS(stat))
1010 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1011 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1013 if (timeout && total_ms > timeout)
1014 err("TO: Time limit exceeded");
1015 if (wall_timeout && wall_ms > wall_timeout)
1016 err("TO: Time limit exceeded (wall clock)");
1018 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
1019 total_ms/1000, total_ms%1000,
1020 wall_ms/1000, wall_ms%1000);
1023 else if (WIFSIGNALED(stat))
1025 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1027 err("SG: Caught fatal signal %d", WTERMSIG(stat));
1029 else if (WIFSTOPPED(stat))
1031 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
1033 err("SG: Stopped by signal %d", WSTOPSIG(stat));
1036 die("wait4: unknown status %x, giving up!", stat);
1040 /*** The process running inside the box ***/
1045 if (mkdir("root", 0750) < 0 && errno != EEXIST)
1046 die("mkdir('root'): %m");
1048 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
1049 die("Cannot mount root ramdisk: %m");
1053 if (chroot("root") < 0)
1054 die("Chroot failed: %m");
1056 if (chdir("root/box") < 0)
1057 die("Cannot change current directory: %m");
1061 setup_credentials(void)
1063 if (setresgid(box_gid, box_gid, box_gid) < 0)
1064 die("setresgid: %m");
1065 if (setgroups(0, NULL) < 0)
1066 die("setgroups: %m");
1067 if (setresuid(box_uid, box_uid, box_uid) < 0)
1068 die("setresuid: %m");
1078 if (open(redir_stdin, O_RDONLY) != 0)
1079 die("open(\"%s\"): %m", redir_stdin);
1084 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1085 die("open(\"%s\"): %m", redir_stdout);
1090 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1091 die("open(\"%s\"): %m", redir_stderr);
1098 setup_rlim(const char *res_name, int res, rlim_t limit)
1100 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
1101 if (setrlimit(res, &rl) < 0)
1102 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
1108 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
1111 RLIM(AS, memory_limit * 1024);
1113 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
1118 RLIM(NPROC, max_processes);
1124 box_inside(void *arg)
1127 write_errors_to_fd = error_pipes[1];
1128 close(error_pipes[0]);
1132 setup_credentials();
1135 char **env = setup_environment();
1137 execve(args[0], args, env);
1138 die("execve(\"%s\"): %m", args[0]);
1144 if (box_id < 0 || box_id >= CONFIG_ISOLATE_NUM_BOXES)
1145 die("Sandbox ID out of range (allowed: 0-%d)", CONFIG_ISOLATE_NUM_BOXES-1);
1146 box_uid = CONFIG_ISOLATE_FIRST_UID + box_id;
1147 box_gid = CONFIG_ISOLATE_FIRST_GID + box_id;
1149 snprintf(box_dir, sizeof(box_dir), "%s/%d", CONFIG_ISOLATE_BOX_DIR, box_id);
1151 if (chdir(box_dir) < 0)
1152 die("chdir(%s): %m", box_dir);
1160 msg("Preparing sandbox directory\n");
1161 xsystem("rm -rf box");
1162 if (mkdir("box", 0700) < 0)
1163 die("Cannot create box: %m");
1164 if (chown("box", orig_uid, orig_gid) < 0)
1165 die("Cannot chown box: %m");
1176 if (!dir_exists("box"))
1177 die("Box directory not found, there isn't anything to clean up");
1179 msg("Deleting sandbox directory\n");
1180 xsystem("rm -rf *");
1181 if (rmdir(box_dir) < 0)
1182 die("Cannot remove %s: %m", box_dir);
1189 if (!dir_exists("box"))
1190 die("Box directory not found, did you run `isolate --init'?");
1193 snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", box_uid, box_gid);
1195 snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
1197 if (pipe(error_pipes) < 0)
1199 for (int i=0; i<2; i++)
1200 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
1201 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
1202 die("fcntl on pipe: %m");
1205 box_inside, // Function to execute as the body of the new process
1206 argv, // Pass our stack
1207 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
1208 argv); // Pass the arguments
1212 die("clone returned 0");
1219 printf("Process isolator 1.0\n");
1220 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
1221 printf("\nCompile-time configuration:\n");
1222 printf("Sandbox directory: %s\n", CONFIG_ISOLATE_BOX_DIR);
1223 printf("Sandbox credentials: uid=%u-%u gid=%u-%u\n",
1224 CONFIG_ISOLATE_FIRST_UID,
1225 CONFIG_ISOLATE_FIRST_UID + CONFIG_ISOLATE_NUM_BOXES - 1,
1226 CONFIG_ISOLATE_FIRST_GID,
1227 CONFIG_ISOLATE_FIRST_GID + CONFIG_ISOLATE_NUM_BOXES - 1);
1232 static void __attribute__((format(printf,1,2)))
1233 usage(const char *msg, ...)
1238 va_start(args, msg);
1239 vfprintf(stderr, msg, args);
1243 Usage: isolate [<options>] <command>\n\
1246 -b, --box-id=<id>\tWhen multiple sandboxes are used in parallel, each must get a unique ID\n\
1247 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
1248 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
1249 --cg-timing\t\tTime limits affects total run time of the control group\n\
1250 -d, --dir=<dir>\t\tMake a directory <dir> visible inside the sandbox\n\
1251 --dir=<in>=<out>\tMake a directory <out> outside visible as <in> inside\n\
1252 --dir=<in>=\t\tDelete a previously defined directory rule (even a default one)\n\
1253 --dir=...:<opt>\tSpecify options for a rule:\n\
1254 \t\t\t\tdev\tAllow access to special files\n\
1255 \t\t\t\tfs\tMount a filesystem (e.g., --dir=/proc:proc:fs)\n\
1256 \t\t\t\tmaybe\tSkip the rule if <out> does not exist\n\
1257 \t\t\t\tnoexec\tDo not allow execution of binaries\n\
1258 \t\t\t\trw\tAllow read-write access\n\
1259 -E, --env=<var>\t\tInherit the environment variable <var> from the parent process\n\
1260 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1261 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1262 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1263 -e, --full-env\t\tInherit full environment of the parent process\n\
1264 -m, --mem=<size>\tLimit address space to <size> KB\n\
1265 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
1266 -q, --quota=<blk>,<ino>\tSet disk quota to <blk> blocks and <ino> inodes\n\
1267 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1268 -r, --stderr=<file>\tRedirect stderr to <file>\n\
1269 -i, --stdin=<file>\tRedirect stdin from <file>\n\
1270 -o, --stdout=<file>\tRedirect stdout to <file>\n\
1271 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
1272 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
1273 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
1274 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1277 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
1278 --run -- <cmd> ...\tRun given command within sandbox\n\
1279 --cleanup\t\tClean up sandbox\n\
1280 --version\t\tDisplay program version and configuration\n\
1294 static const char short_opts[] = "b:c:d:eE:i:k:m:M:o:p::q:r:t:vw:x:";
1296 static const struct option long_opts[] = {
1297 { "box-id", 1, NULL, 'b' },
1298 { "cg", 1, NULL, 'c' },
1299 { "cg-mem", 1, NULL, OPT_CG_MEM },
1300 { "cg-timing", 0, NULL, OPT_CG_TIMING },
1301 { "cleanup", 0, NULL, OPT_CLEANUP },
1302 { "dir", 1, NULL, 'd' },
1303 { "env", 1, NULL, 'E' },
1304 { "extra-time", 1, NULL, 'x' },
1305 { "full-env", 0, NULL, 'e' },
1306 { "init", 0, NULL, OPT_INIT },
1307 { "mem", 1, NULL, 'm' },
1308 { "meta", 1, NULL, 'M' },
1309 { "processes", 2, NULL, 'p' },
1310 { "quota", 1, NULL, 'q' },
1311 { "run", 0, NULL, OPT_RUN },
1312 { "stack", 1, NULL, 'k' },
1313 { "stderr", 1, NULL, 'r' },
1314 { "stdin", 1, NULL, 'i' },
1315 { "stdout", 1, NULL, 'o' },
1316 { "time", 1, NULL, 't' },
1317 { "verbose", 0, NULL, 'v' },
1318 { "version", 0, NULL, OPT_VERSION },
1319 { "wall-time", 1, NULL, 'w' },
1320 { NULL, 0, NULL, 0 }
1324 main(int argc, char **argv)
1328 enum opt_code mode = 0;
1332 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1336 box_id = atoi(optarg);
1342 if (!set_dir_action(optarg))
1343 usage("Invalid directory specified: %s\n", optarg);
1349 if (!set_env_action(optarg))
1350 usage("Invalid environment specified: %s\n", optarg);
1353 stack_limit = atoi(optarg);
1356 redir_stdin = optarg;
1359 memory_limit = atoi(optarg);
1365 redir_stdout = optarg;
1369 max_processes = atoi(optarg);
1374 sep = strchr(optarg, ',');
1376 usage("Invalid quota specified: %s\n", optarg);
1377 block_quota = atoi(optarg);
1378 inode_quota = atoi(sep+1);
1381 redir_stderr = optarg;
1384 timeout = 1000*atof(optarg);
1390 wall_timeout = 1000*atof(optarg);
1393 extra_timeout = 1000*atof(optarg);
1402 cg_memory_limit = atoi(optarg);
1412 usage("Please specify an isolate command (e.g. --init, --run).\n");
1413 if (mode == OPT_VERSION)
1420 die("Must be started as root");
1421 orig_uid = getuid();
1422 orig_gid = getgid();
1432 usage("--init mode takes no parameters\n");
1437 usage("--run mode requires a command to run\n");
1442 usage("--cleanup mode takes no parameters\n");
1446 die("Internal error: mode mismatch");