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>
26 #include <sys/signal.h>
27 #include <sys/resource.h>
28 #include <sys/mount.h>
31 #define NONRET __attribute__((noreturn))
32 #define UNUSED __attribute__((unused))
33 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
35 #define BOX_DIR CONFIG_ISOLATE_BOX_DIR
36 #define BOX_UID CONFIG_ISOLATE_BOX_UID
37 #define BOX_GID CONFIG_ISOLATE_BOX_GID
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 max_processes = 1;
47 static char *redir_stdin, *redir_stdout, *redir_stderr;
50 static int cg_memory_limit;
52 static char *cg_root = "/sys/fs/cgroup";
54 static uid_t orig_uid;
55 static gid_t orig_gid;
58 static int partial_line;
59 static char cleanup_cmd[256];
61 static struct timeval start_time;
62 static int ticks_per_sec;
63 static int total_ms, wall_ms;
64 static volatile sig_atomic_t timer_tick;
66 static int error_pipes[2];
67 static int write_errors_to_fd;
68 static int read_errors_from_fd;
70 static void die(char *msg, ...) NONRET;
71 static void cg_stats(void);
72 static int get_wall_time_ms(void);
73 static int get_run_time_ms(struct rusage *rus);
77 static FILE *metafile;
80 meta_open(const char *name)
82 if (!strcmp(name, "-"))
87 metafile = fopen(name, "w");
89 die("Failed to open metafile '%s'",name);
95 if (metafile && metafile != stdout)
99 static void __attribute__((format(printf,1,2)))
100 meta_printf(const char *fmt, ...)
107 vfprintf(metafile, fmt, args);
112 final_stats(struct rusage *rus)
114 total_ms = get_run_time_ms(rus);
115 wall_ms = get_wall_time_ms();
117 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
118 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
119 meta_printf("max-rss:%ld\n", rus->ru_maxrss);
120 meta_printf("csw-voluntary:%ld\n", rus->ru_nvcsw);
121 meta_printf("csw-forced:%ld\n", rus->ru_nivcsw);
126 /*** Messages and exits ***/
129 xsystem(const char *cmd)
131 int ret = system(cmd);
133 die("system(\"%s\"): %m", cmd);
134 if (!WIFEXITED(ret) || WEXITSTATUS(ret))
135 die("system(\"%s\"): Exited with status %d", cmd, ret);
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_cmd[0])
159 xsystem(cleanup_cmd);
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);
238 void *p = malloc(size);
240 die("Out of memory");
244 /*** Environment rules ***/
247 char *var; // Variable to match
248 char *val; // ""=clear, NULL=inherit
250 struct env_rule *next;
253 static struct env_rule *first_env_rule;
254 static struct env_rule **last_env_rule = &first_env_rule;
256 static struct env_rule default_env_rules[] = {
257 { "LIBC_FATAL_STDERR_", "1" }
261 set_env_action(char *a0)
263 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
264 char *a = (char *)(r+1);
267 char *sep = strchr(a, '=');
279 last_env_rule = &r->next;
285 match_env_var(char *env_entry, struct env_rule *r)
287 if (strncmp(env_entry, r->var, r->var_len))
289 return (env_entry[r->var_len] == '=');
293 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
295 // First remove the variable if already set
297 while (pos < *env_sizep && !match_env_var(env[pos], r))
299 if (pos < *env_sizep)
302 env[pos] = env[*env_sizep];
303 env[*env_sizep] = NULL;
306 // What is the new value?
312 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
313 sprintf(new, "%s=%s", r->var, r->val);
318 while (environ[pos] && !match_env_var(environ[pos], r))
320 if (!(new = environ[pos]))
324 // Add it at the end of the array
325 env[(*env_sizep)++] = new;
326 env[*env_sizep] = NULL;
330 setup_environment(void)
332 // Link built-in rules with user rules
333 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
335 default_env_rules[i].next = first_env_rule;
336 first_env_rule = &default_env_rules[i];
339 // Scan the original environment
340 char **orig_env = environ;
342 while (orig_env[orig_size])
345 // For each rule, reserve one more slot and calculate length
347 for (struct env_rule *r = first_env_rule; r; r=r->next)
350 r->var_len = strlen(r->var);
353 // Create a new environment
354 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
358 memcpy(env, environ, orig_size * sizeof(char *));
365 // Apply the rules one by one
366 for (struct env_rule *r = first_env_rule; r; r=r->next)
367 apply_env_rule(env, &size, r);
369 // Return the new env and pass some gossip
372 fprintf(stderr, "Passing environment:\n");
373 for (int i=0; env[i]; i++)
374 fprintf(stderr, "\t%s\n", env[i]);
379 /*** Control groups ***/
381 static char cg_path[256];
383 #define CG_BUFSIZE 1024
386 cg_read(char *attr, char *buf)
396 snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
398 int fd = open(path, O_RDONLY);
403 die("Cannot read %s: %m", path);
406 int n = read(fd, buf, CG_BUFSIZE);
408 die("Cannot read %s: %m", path);
409 if (n >= CG_BUFSIZE - 1)
410 die("Attribute %s too long", path);
411 if (n > 0 && buf[n-1] == '\n')
416 msg("CG: Read %s = %s\n", attr, buf);
422 static void __attribute__((format(printf,2,3)))
423 cg_write(char *attr, char *fmt, ...)
428 char buf[CG_BUFSIZE];
429 int n = vsnprintf(buf, sizeof(buf), fmt, args);
431 die("cg_writef: Value for attribute %s is too long", attr);
434 msg("CG: Write %s = %s", attr, buf);
437 snprintf(path, sizeof(path), "%s/%s", cg_path, attr);
439 int fd = open(path, O_WRONLY | O_TRUNC);
441 die("Cannot write %s: %m", path);
443 int written = write(fd, buf, n);
445 die("Cannot set %s to %s: %m", path, buf);
447 die("Short write to %s (%d out of %d bytes)", path, written, n);
460 if (stat(cg_root, &st) < 0 || !S_ISDIR(st.st_mode))
461 die("Control group filesystem at %s not mounted", cg_root);
463 snprintf(cg_path, sizeof(cg_path), "%s/box-%d", cg_root, BOX_UID);
464 msg("Using control group %s\n", cg_path);
474 char buf[CG_BUFSIZE];
476 if (stat(cg_path, &st) >= 0 || errno != ENOENT)
478 msg("Control group %s already exists, trying to empty it.\n", cg_path);
479 if (rmdir(cg_path) < 0)
480 die("Failed to reset control group %s: %m", cg_path);
483 if (mkdir(cg_path, 0777) < 0)
484 die("Failed to create control group %s: %m", cg_path);
486 // If cpuset module is enabled, copy allowed cpus and memory nodes from parent group
487 if (cg_read("?../cpuset.cpus", buf))
488 cg_write("cpuset.cpus", "%s", buf);
489 if (cg_read("?../cpuset.mems", buf))
490 cg_write("cpuset.mems", "%s", buf);
499 msg("Entering control group %s\n", cg_path);
502 if (stat(cg_path, &st) < 0)
503 die("Control group %s does not exist: %m", cg_path);
507 cg_write("memory.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
508 cg_write("memory.memsw.limit_in_bytes", "%lld\n", (long long) cg_memory_limit << 10);
512 cg_write("cpuacct.usage", "0\n");
514 cg_write("tasks", "%d\n", (int) getpid());
518 cg_get_run_time_ms(void)
523 char buf[CG_BUFSIZE];
524 cg_read("cpuacct.usage", buf);
525 unsigned long long ns = atoll(buf);
535 char buf[CG_BUFSIZE];
537 // Memory usage statistics
538 unsigned long long mem=0, memsw=0;
539 if (cg_read("?memory.max_usage_in_bytes", buf))
541 if (cg_read("?memory.memsw.max_usage_in_bytes", buf))
548 meta_printf("cg-mem:%lld\n", mem >> 10);
554 char buf[CG_BUFSIZE];
559 cg_read("tasks", buf);
561 die("Some tasks left in control group %s, failed to remove it", cg_path);
563 if (rmdir(cg_path) < 0)
564 die("Cannot remove control group %s: %m", cg_path);
567 /*** The keeper process ***/
570 signal_alarm(int unused UNUSED)
572 /* Time limit checks are synchronous, so we only schedule them there. */
578 signal_int(int unused UNUSED)
580 /* Interrupts are fatal, so no synchronization requirements. */
581 meta_printf("exitsig:%d\n", SIGINT);
582 err("SG: Interrupted");
585 #define PROC_BUF_SIZE 4096
587 read_proc_file(char *buf, char *name, int *fdp)
593 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
594 *fdp = open(buf, O_RDONLY);
596 die("open(%s): %m", buf);
598 lseek(*fdp, 0, SEEK_SET);
599 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
600 die("read on /proc/$pid/%s: %m", name);
601 if (c >= PROC_BUF_SIZE-1)
602 die("/proc/$pid/%s too long", name);
607 get_wall_time_ms(void)
609 struct timeval now, wall;
610 gettimeofday(&now, NULL);
611 timersub(&now, &start_time, &wall);
612 return wall.tv_sec*1000 + wall.tv_usec/1000;
616 get_run_time_ms(struct rusage *rus)
619 return cg_get_run_time_ms();
623 struct timeval total;
624 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
625 return total.tv_sec*1000 + total.tv_usec/1000;
628 char buf[PROC_BUF_SIZE], *x;
630 static int proc_stat_fd;
632 read_proc_file(buf, "stat", &proc_stat_fd);
634 while (*x && *x != ' ')
639 die("proc stat syntax error 1");
640 while (*x && (*x != ')' || x[1] != ' '))
642 while (*x == ')' || *x == ' ')
644 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
645 die("proc stat syntax error 2");
647 return (utime + stime) * 1000 / ticks_per_sec;
655 int wall_ms = get_wall_time_ms();
656 if (wall_ms > wall_timeout)
657 err("TO: Time limit exceeded (wall clock)");
659 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
663 int ms = get_run_time_ms(NULL);
665 fprintf(stderr, "[time check: %d msec]\n", ms);
666 if (ms > timeout && ms > extra_timeout)
667 err("TO: Time limit exceeded");
674 read_errors_from_fd = error_pipes[0];
675 close(error_pipes[1]);
678 bzero(&sa, sizeof(sa));
679 sa.sa_handler = signal_int;
680 sigaction(SIGINT, &sa, NULL);
682 gettimeofday(&start_time, NULL);
683 ticks_per_sec = sysconf(_SC_CLK_TCK);
684 if (ticks_per_sec <= 0)
685 die("Invalid ticks_per_sec!");
687 if (timeout || wall_timeout)
689 sa.sa_handler = signal_alarm;
690 sigaction(SIGALRM, &sa, NULL);
704 p = wait4(box_pid, &stat, 0, &rus);
712 die("wait4: unknown pid %d exited!", p);
715 // Check error pipe if there is an internal error passed from inside the box
717 int n = read(read_errors_from_fd, interr, sizeof(interr) - 1);
727 if (WEXITSTATUS(stat))
729 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
730 err("RE: Exited with error status %d", WEXITSTATUS(stat));
732 if (timeout && total_ms > timeout)
733 err("TO: Time limit exceeded");
734 if (wall_timeout && wall_ms > wall_timeout)
735 err("TO: Time limit exceeded (wall clock)");
737 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall)\n",
738 total_ms/1000, total_ms%1000,
739 wall_ms/1000, wall_ms%1000);
742 else if (WIFSIGNALED(stat))
744 meta_printf("exitsig:%d\n", WTERMSIG(stat));
746 err("SG: Caught fatal signal %d", WTERMSIG(stat));
748 else if (WIFSTOPPED(stat))
750 meta_printf("exitsig:%d\n", WSTOPSIG(stat));
752 err("SG: Stopped by signal %d", WSTOPSIG(stat));
755 die("wait4: unknown status %x, giving up!", stat);
759 /*** The process running inside the box ***/
764 if (mkdir("root", 0750) < 0 && errno != EEXIST)
765 die("mkdir('root'): %m");
767 if (mount("none", "root", "tmpfs", 0, "mode=755") < 0)
768 die("Cannot mount root ramdisk: %m");
770 static const char * const dirs[] = { "box", "/bin", "/lib", "/lib64", "/usr", "/dev" };
771 for (int i=0; i < ARRAY_SIZE(dirs); i++)
773 const char *d = dirs[i];
775 snprintf(buf, sizeof(buf), "root/%s", (d[0] == '/' ? d+1 : d));
776 msg("Binding %s on %s\n", d, buf);
777 if (mkdir(buf, 0755) < 0)
778 die("mkdir(%s): %m", buf);
779 if (mount(d, buf, "none", MS_BIND | MS_NOSUID | MS_NODEV, "") < 0)
780 die("Cannot bind %s on %s: %m", d, buf);
783 if (mkdir("root/proc", 0755) < 0)
784 die("Cannot create proc: %m");
785 if (mount("none", "root/proc", "proc", 0, "") < 0)
786 die("Cannot mount proc: %m");
788 if (chroot("root") < 0)
789 die("Chroot failed: %m");
791 if (chdir("root/box") < 0)
792 die("Cannot change current directory: %m");
796 setup_credentials(void)
798 if (setresgid(BOX_GID, BOX_GID, BOX_GID) < 0)
799 die("setresgid: %m");
800 if (setgroups(0, NULL) < 0)
801 die("setgroups: %m");
802 if (setresuid(BOX_UID, BOX_UID, BOX_UID) < 0)
803 die("setresuid: %m");
813 if (open(redir_stdin, O_RDONLY) != 0)
814 die("open(\"%s\"): %m", redir_stdin);
819 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
820 die("open(\"%s\"): %m", redir_stdout);
825 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
826 die("open(\"%s\"): %m", redir_stderr);
833 setup_rlim(const char *res_name, int res, rlim_t limit)
835 struct rlimit rl = { .rlim_cur = limit, .rlim_max = limit };
836 if (setrlimit(res, &rl) < 0)
837 die("setrlimit(%s, %jd)", res_name, (intmax_t) limit);
843 #define RLIM(res, val) setup_rlim("RLIMIT_" #res, RLIMIT_##res, val)
846 RLIM(AS, memory_limit * 1024);
848 RLIM(STACK, (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY));
853 RLIM(NPROC, max_processes);
859 box_inside(void *arg)
862 write_errors_to_fd = error_pipes[1];
863 close(error_pipes[0]);
870 char **env = setup_environment();
872 execve(args[0], args, env);
873 die("execve(\"%s\"): %m", args[0]);
881 msg("Preparing sandbox directory\n");
882 xsystem("rm -rf box");
883 if (mkdir("box", 0700) < 0)
884 die("Cannot create box: %m");
885 if (chown("box", orig_uid, orig_gid) < 0)
886 die("Cannot chown box: %m");
895 if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
896 die("Box directory not found, there isn't anything to clean up");
898 msg("Deleting sandbox directory\n");
899 xsystem("rm -rf box");
907 if (stat("box", &st) < 0 || !S_ISDIR(st.st_mode))
908 die("Box directory not found, did you run `isolate --init'?");
911 snprintf(cmd, sizeof(cmd), "chown -R %d.%d box", BOX_UID, BOX_GID);
913 snprintf(cleanup_cmd, sizeof(cleanup_cmd), "chown -R %d.%d box", orig_uid, orig_gid);
915 if (pipe(error_pipes) < 0)
917 for (int i=0; i<2; i++)
918 if (fcntl(error_pipes[i], F_SETFD, fcntl(error_pipes[i], F_GETFD) | FD_CLOEXEC) < 0 ||
919 fcntl(error_pipes[i], F_SETFL, fcntl(error_pipes[i], F_GETFL) | O_NONBLOCK) < 0)
920 die("fcntl on pipe: %m");
923 box_inside, // Function to execute as the body of the new process
924 argv, // Pass our stack
925 SIGCHLD | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWPID,
926 argv); // Pass the arguments
930 die("clone returned 0");
937 printf("Process isolator 1.0\n");
938 printf("(c) 2012 Martin Mares and Bernard Blackham\n");
939 printf("\nCompile-time configuration:\n");
940 printf("Sandbox directory: %s\n", BOX_DIR);
941 printf("Sandbox credentials: uid=%u gid=%u\n", BOX_UID, BOX_GID);
949 fprintf(stderr, "Invalid arguments!\n");
951 Usage: isolate [<options>] <command>\n\
954 -c, --cg[=<parent>]\tPut process in a control group (optionally a sub-group of <parent>)\n\
955 --cg-mem=<size>\tLimit memory usage of the control group to <size> KB\n\
956 --cg-timing\t\tTime limits affects total run time of the control group\n\
957 -E, --env=<var>\tInherit the environment variable <var> from the parent process\n\
958 -E, --env=<var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
959 -x, --extra-time=<time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
960 \t\t\tso that its real execution time is reported (seconds, fractions allowed)\n\
961 -e, --full-env\t\tInherit full environment of the parent process\n\
962 -m, --mem=<size>\tLimit address space to <size> KB\n\
963 -M, --meta=<file>\tOutput process information to <file> (name:value)\n\
964 -k, --stack=<size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
965 -r, --stderr=<file>\tRedirect stderr to <file>\n\
966 -i, --stdin=<file>\tRedirect stdin from <file>\n\
967 -o, --stdout=<file>\tRedirect stdout to <file>\n\
968 -p, --processes[=<max>]\tEnable multiple processes (at most <max> of them); needs --cg\n\
969 -t, --time=<time>\tSet run time limit (seconds, fractions allowed)\n\
970 -v, --verbose\t\tBe verbose (use multiple times for even more verbosity)\n\
971 -w, --wall-time=<time>\tSet wall clock time limit (seconds, fractions allowed)\n\
974 --init\t\tInitialize sandbox (and its control group when --cg is used)\n\
975 --run -- <cmd> ...\tRun given command within sandbox\n\
976 --cleanup\t\tClean up sandbox\n\
977 --version\t\tDisplay program version and configuration\n\
991 static const char short_opts[] = "c::eE:i:k:m:M:o:p::r:t:vw:x:";
993 static const struct option long_opts[] = {
994 { "cg", 2, NULL, 'c' },
995 { "cg-mem", 1, NULL, OPT_CG_MEM },
996 { "cg-timing", 0, NULL, OPT_CG_TIMING },
997 { "cleanup", 0, NULL, OPT_CLEANUP },
998 { "env", 1, NULL, 'E' },
999 { "extra-time", 1, NULL, 'x' },
1000 { "full-env", 0, NULL, 'e' },
1001 { "init", 0, NULL, OPT_INIT },
1002 { "mem", 1, NULL, 'm' },
1003 { "meta", 1, NULL, 'M' },
1004 { "processes", 2, NULL, 'p' },
1005 { "run", 0, NULL, OPT_RUN },
1006 { "stack", 1, NULL, 'k' },
1007 { "stderr", 1, NULL, 'r' },
1008 { "stdin", 1, NULL, 'i' },
1009 { "stdout", 1, NULL, 'o' },
1010 { "time", 1, NULL, 't' },
1011 { "verbose", 0, NULL, 'v' },
1012 { "version", 0, NULL, OPT_VERSION },
1013 { "wall-time", 1, NULL, 'w' },
1014 { NULL, 0, NULL, 0 }
1018 main(int argc, char **argv)
1021 enum opt_code mode = 0;
1023 while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) >= 0)
1035 if (!set_env_action(optarg))
1039 stack_limit = atoi(optarg);
1042 redir_stdin = optarg;
1045 memory_limit = atoi(optarg);
1051 redir_stdout = optarg;
1055 max_processes = atoi(optarg);
1060 redir_stderr = optarg;
1063 timeout = 1000*atof(optarg);
1069 wall_timeout = 1000*atof(optarg);
1072 extra_timeout = 1000*atof(optarg);
1081 cg_memory_limit = atoi(optarg);
1092 if (mode == OPT_VERSION)
1099 die("Must be started as root");
1100 orig_uid = getuid();
1101 orig_gid = getgid();
1104 if (chdir(BOX_DIR) < 0)
1105 die("chdir(%s): %m", BOX_DIR);
1126 die("Internal error: mode mismatch");