2 * A Simple Sandbox for MO-Eval
4 * (c) 2001--2008 Martin Mares <mj@ucw.cz>
7 #define _LARGEFILE64_SOURCE
22 #include <sys/ptrace.h>
23 #include <sys/signal.h>
24 #include <sys/sysinfo.h>
25 #include <sys/syscall.h>
26 #include <sys/resource.h>
28 #define NONRET __attribute__((noreturn))
29 #define UNUSED __attribute__((unused))
30 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
32 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
33 static int timeout; /* milliseconds */
34 static int wall_timeout;
35 static int pass_environ;
36 static int file_access;
38 static int memory_limit;
39 static char *redir_stdin, *redir_stdout, *redir_stderr;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static struct timeval start_time;
46 static int ticks_per_sec;
48 static int partial_line;
50 static int mem_peak_kb;
51 static int total_ms, wall_ms;
53 static void die(char *msg, ...) NONRET;
54 static void sample_mem_peak(void);
58 static FILE *metafile;
61 meta_open(const char *name)
63 if (!strcmp(name, "-"))
68 metafile = fopen(name, "w");
70 die("Failed to open metafile '%s'",name);
76 if (metafile && metafile != stdout)
80 static void __attribute__((format(printf,1,2)))
81 meta_printf(const char *fmt, ...)
88 vfprintf(metafile, fmt, args);
93 final_stats(struct rusage *rus)
95 struct timeval total, now, wall;
96 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
97 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
98 gettimeofday(&now, NULL);
99 timersub(&now, &start_time, &wall);
100 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
102 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
103 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
104 meta_printf("mem:%llu\n", (unsigned long long) mem_peak_kb * 1024);
107 /*** Messages and exits ***/
116 ptrace(PTRACE_KILL, box_pid);
117 kill(-box_pid, SIGKILL);
118 kill(box_pid, SIGKILL);
122 int p = wait4(box_pid, &stat, 0, &rus);
124 fprintf(stderr, "UGH: Lost track of the process\n");
140 /* Report an error of the sandbox itself */
141 static void NONRET __attribute__((format(printf,1,2)))
148 vsnprintf(buf, sizeof(buf), msg, args);
149 meta_printf("status:XX\nmessage:%s\n", buf);
155 /* Report an error of the program inside the sandbox */
156 static void NONRET __attribute__((format(printf,1,2)))
162 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
164 meta_printf("status:%c%c\n", msg[0], msg[1]);
168 vsnprintf(buf, sizeof(buf), msg, args);
169 meta_printf("message:%s\n", buf);
175 /* Write a message, but only if in verbose mode */
176 static void __attribute__((format(printf,1,2)))
183 int len = strlen(msg);
185 partial_line = (msg[len-1] != '\n');
186 vfprintf(stderr, msg, args);
195 void *p = malloc(size);
197 die("Out of memory");
201 /*** Syscall rules ***/
203 static const char * const syscall_names[] = {
204 #include "box/syscall-table.h"
206 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
207 #define NUM_ACTIONS (NUM_SYSCALLS+64)
210 A_DEFAULT, // Use the default action
211 A_NO, // Always forbid
212 A_YES, // Always permit
213 A_FILENAME, // Permit if arg1 is a known filename
215 A_SAMPLE_MEM = 64, // Sample memory usage before the syscall
216 A_LIBERAL = 128, // Valid only in liberal mode
217 // Must fit in a unsigned char
220 static unsigned char syscall_action[NUM_ACTIONS] = {
221 #define S(x) [__NR_##x]
223 // Syscalls permitted for specific file names
224 S(open) = A_FILENAME,
225 S(creat) = A_FILENAME,
226 S(unlink) = A_FILENAME,
227 S(oldstat) = A_FILENAME,
228 S(access) = A_FILENAME,
229 S(oldlstat) = A_FILENAME,
230 S(truncate) = A_FILENAME,
231 S(stat) = A_FILENAME,
232 S(lstat) = A_FILENAME,
233 S(truncate64) = A_FILENAME,
234 S(stat64) = A_FILENAME,
235 S(lstat64) = A_FILENAME,
236 S(readlink) = A_FILENAME,
238 // Syscalls permitted always
239 S(exit) = A_YES | A_SAMPLE_MEM,
253 S(ftruncate) = A_YES,
255 S(personality) = A_YES,
259 S(getresuid) = A_YES,
267 S(ftruncate64) = A_YES,
277 S(set_thread_area) = A_YES,
278 S(get_thread_area) = A_YES,
279 S(set_tid_address) = A_YES,
280 S(exit_group) = A_YES | A_SAMPLE_MEM,
282 // Syscalls permitted only in liberal mode
283 S(time) = A_YES | A_LIBERAL,
284 S(alarm) = A_YES | A_LIBERAL,
285 S(pause) = A_YES | A_LIBERAL,
286 S(signal) = A_YES | A_LIBERAL,
287 S(fchmod) = A_YES | A_LIBERAL,
288 S(sigaction) = A_YES | A_LIBERAL,
289 S(sgetmask) = A_YES | A_LIBERAL,
290 S(ssetmask) = A_YES | A_LIBERAL,
291 S(sigsuspend) = A_YES | A_LIBERAL,
292 S(sigpending) = A_YES | A_LIBERAL,
293 S(getrlimit) = A_YES | A_LIBERAL,
294 S(getrusage) = A_YES | A_LIBERAL,
295 S(ugetrlimit) = A_YES | A_LIBERAL,
296 S(gettimeofday) = A_YES | A_LIBERAL,
297 S(select) = A_YES | A_LIBERAL,
298 S(readdir) = A_YES | A_LIBERAL,
299 S(setitimer) = A_YES | A_LIBERAL,
300 S(getitimer) = A_YES | A_LIBERAL,
301 S(sigreturn) = A_YES | A_LIBERAL,
302 S(mprotect) = A_YES | A_LIBERAL,
303 S(sigprocmask) = A_YES | A_LIBERAL,
304 S(getdents) = A_YES | A_LIBERAL,
305 S(getdents64) = A_YES | A_LIBERAL,
306 S(_newselect) = A_YES | A_LIBERAL,
307 S(fdatasync) = A_YES | A_LIBERAL,
308 S(mremap) = A_YES | A_LIBERAL,
309 S(poll) = A_YES | A_LIBERAL,
310 S(getcwd) = A_YES | A_LIBERAL,
311 S(nanosleep) = A_YES | A_LIBERAL,
312 S(rt_sigreturn) = A_YES | A_LIBERAL,
313 S(rt_sigaction) = A_YES | A_LIBERAL,
314 S(rt_sigprocmask) = A_YES | A_LIBERAL,
315 S(rt_sigpending) = A_YES | A_LIBERAL,
316 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
317 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
318 S(rt_sigsuspend) = A_YES | A_LIBERAL,
319 S(_sysctl) = A_YES | A_LIBERAL,
324 syscall_name(unsigned int id, char *buf)
326 if (id < NUM_SYSCALLS && syscall_names[id])
327 return syscall_names[id];
330 sprintf(buf, "#%d", id);
336 syscall_by_name(char *name)
338 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
339 if (syscall_names[i] && !strcmp(syscall_names[i], name))
346 unsigned long l = strtoul(name, &ep, 0);
349 if (l >= NUM_ACTIONS)
355 set_syscall_action(char *a)
357 char *sep = strchr(a, '=');
358 enum action act = A_YES;
362 if (!strcmp(sep, "yes"))
364 else if (!strcmp(sep, "no"))
366 else if (!strcmp(sep, "file"))
372 int sys = syscall_by_name(a);
374 die("Unknown syscall `%s'", a);
375 if (sys >= NUM_ACTIONS)
376 die("Syscall `%s' out of range", a);
377 syscall_action[sys] = act;
386 struct path_rule *next;
389 static struct path_rule default_path_rules[] = {
392 { "/usr/lib/", A_YES },
393 { "/opt/lib/", A_YES },
394 { "/usr/share/zoneinfo/", A_YES },
395 { "/usr/share/locale/", A_YES },
396 { "/dev/null", A_YES },
397 { "/dev/zero", A_YES },
398 { "/proc/meminfo", A_YES },
399 { "/proc/self/stat", A_YES },
400 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
403 static struct path_rule *user_path_rules;
404 static struct path_rule **last_path_rule = &user_path_rules;
407 set_path_action(char *a)
409 char *sep = strchr(a, '=');
410 enum action act = A_YES;
414 if (!strcmp(sep, "yes"))
416 else if (!strcmp(sep, "no"))
422 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
423 r->path = (char *)(r+1);
428 last_path_rule = &r->next;
433 match_path_rule(struct path_rule *r, char *path)
437 if (*rr++ != *path++)
439 if (rr[-1] == '/' && !path[-1])
443 if (rr > r->path && rr[-1] != '/' && *path)
448 /*** Environment rules ***/
451 char *var; // Variable to match
452 char *val; // ""=clear, NULL=inherit
454 struct env_rule *next;
457 static struct env_rule *first_env_rule;
458 static struct env_rule **last_env_rule = &first_env_rule;
460 static struct env_rule default_env_rules[] = {
461 { "LIBC_FATAL_STDERR_", "1" }
465 set_env_action(char *a0)
467 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
468 char *a = (char *)(r+1);
471 char *sep = strchr(a, '=');
483 last_env_rule = &r->next;
489 match_env_var(char *env_entry, struct env_rule *r)
491 if (strncmp(env_entry, r->var, r->var_len))
493 return (env_entry[r->var_len] == '=');
497 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
499 // First remove the variable if already set
501 while (pos < *env_sizep && !match_env_var(env[pos], r))
503 if (pos < *env_sizep)
506 env[pos] = env[*env_sizep];
507 env[*env_sizep] = NULL;
510 // What is the new value?
516 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
517 sprintf(new, "%s=%s", r->var, r->val);
522 while (environ[pos] && !match_env_var(environ[pos], r))
524 if (!(new = environ[pos]))
528 // Add it at the end of the array
529 env[(*env_sizep)++] = new;
530 env[*env_sizep] = NULL;
534 setup_environment(void)
536 // Link built-in rules with user rules
537 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
539 default_env_rules[i].next = first_env_rule;
540 first_env_rule = &default_env_rules[i];
543 // Scan the original environment
544 char **orig_env = environ;
546 while (orig_env[orig_size])
549 // For each rule, reserve one more slot and calculate length
551 for (struct env_rule *r = first_env_rule; r; r=r->next)
554 r->var_len = strlen(r->var);
557 // Create a new environment
558 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
562 memcpy(env, environ, orig_size * sizeof(char *));
569 // Apply the rules one by one
570 for (struct env_rule *r = first_env_rule; r; r=r->next)
571 apply_env_rule(env, &size, r);
573 // Return the new env and pass some gossip
576 fprintf(stderr, "Passing environment:\n");
577 for (int i=0; env[i]; i++)
578 fprintf(stderr, "\t%s\n", env[i]);
583 /*** Syscall checks ***/
586 valid_filename(unsigned long addr)
588 char namebuf[4096], *p, *end;
592 err("FA: File access forbidden");
593 if (file_access >= 9)
598 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
599 mem_fd = open(namebuf, O_RDONLY);
601 die("open(%s): %m", namebuf);
608 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
609 int l = namebuf + sizeof(namebuf) - end;
613 err("FA: Access to file with name too long");
614 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
615 die("lseek64(mem): %m");
616 remains = read(mem_fd, end, l);
618 die("read(mem): %m");
620 err("FA: Access to file with name out of memory");
627 msg("[%s] ", namebuf);
628 if (file_access >= 3)
631 // Everything in current directory is permitted
632 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
635 // ".." anywhere in the path is forbidden
636 enum action act = A_DEFAULT;
637 if (strstr(namebuf, ".."))
641 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
642 act = match_path_rule(r, namebuf);
644 // Scan built-in rules
645 if (file_access >= 2)
646 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
647 act = match_path_rule(&default_path_rules[i], namebuf);
650 err("FA: Forbidden access to file `%s'", namebuf);
653 // Check syscall. If invalid, return -1, otherwise return the action mask.
655 valid_syscall(struct user *u)
657 unsigned int sys = u->regs.orig_eax;
658 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
662 if (filter_syscalls != 1)
666 switch (act & A_ACTION_MASK)
673 valid_filename(u->regs.ebx);
681 if (u->regs.ebx == box_pid)
683 meta_printf("exitsig:%d\n", (int)u->regs.ecx);
684 err("SG: Committed suicide by signal %d", (int)u->regs.ecx);
688 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
690 meta_printf("exitsig:%d\n", (int)u->regs.edx);
691 err("SG: Committed suicide by signal %d", (int)u->regs.edx);
700 signal_alarm(int unused UNUSED)
702 /* Time limit checks are synchronous, so we only schedule them there. */
708 signal_int(int unused UNUSED)
710 /* Interrupts are fatal, so no synchronization requirements. */
711 meta_printf("exitsig:%d\n", SIGINT);
712 err("SG: Interrupted");
715 #define PROC_BUF_SIZE 4096
717 read_proc_file(char *buf, char *name, int *fdp)
723 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
724 *fdp = open(buf, O_RDONLY);
726 die("open(%s): %m", buf);
728 lseek(*fdp, 0, SEEK_SET);
729 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
730 die("read on /proc/$pid/%s: %m", name);
731 if (c >= PROC_BUF_SIZE-1)
732 die("/proc/$pid/%s too long", name);
741 struct timeval now, wall;
743 gettimeofday(&now, NULL);
744 timersub(&now, &start_time, &wall);
745 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
746 if (wall_ms > wall_timeout)
747 err("TO: Time limit exceeded (wall clock)");
749 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
753 char buf[PROC_BUF_SIZE], *x;
754 int utime, stime, ms;
755 static int proc_stat_fd;
756 read_proc_file(buf, "stat", &proc_stat_fd);
758 while (*x && *x != ' ')
763 die("proc stat syntax error 1");
764 while (*x && (*x != ')' || x[1] != ' '))
766 while (*x == ')' || *x == ' ')
768 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
769 die("proc stat syntax error 2");
770 ms = (utime + stime) * 1000 / ticks_per_sec;
772 fprintf(stderr, "[time check: %d msec]\n", ms);
774 err("TO: Time limit exceeded");
779 sample_mem_peak(void)
782 * We want to find out the peak memory usage of the process, which is
783 * maintained by the kernel, but unforunately it gets lost when the
784 * process exits (it is not reported in struct rusage). Therefore we
785 * have to sample it whenever we suspect that the process is about
788 char buf[PROC_BUF_SIZE], *x;
789 static int proc_status_fd;
790 read_proc_file(buf, "status", &proc_status_fd);
796 while (*x && *x != ':' && *x != '\n')
798 if (!*x || *x == '\n')
801 while (*x == ' ' || *x == '\t')
805 while (*x && *x != '\n')
811 if (!strcmp(key, "VmPeak"))
813 int peak = atoi(val);
814 if (peak > mem_peak_kb)
820 msg("[mem-peak: %u KB]\n", mem_peak_kb);
826 int syscall_count = 0;
830 bzero(&sa, sizeof(sa));
831 sa.sa_handler = signal_int;
832 sigaction(SIGINT, &sa, NULL);
833 gettimeofday(&start_time, NULL);
834 ticks_per_sec = sysconf(_SC_CLK_TCK);
835 if (ticks_per_sec <= 0)
836 die("Invalid ticks_per_sec!");
837 if (timeout || wall_timeout)
839 sa.sa_handler = signal_alarm;
840 sigaction(SIGALRM, &sa, NULL);
853 p = wait4(box_pid, &stat, WUNTRACED, &rus);
861 die("wait4: unknown pid %d exited!", p);
866 if (WEXITSTATUS(stat))
870 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
871 err("RE: Exited with error status %d", WEXITSTATUS(stat));
875 // Internal error happened inside the child process and it has been already reported.
879 if (timeout && total_ms > timeout)
880 err("TO: Time limit exceeded");
881 if (wall_timeout && wall_ms > wall_timeout)
882 err("TO: Time limit exceeded (wall clock)");
884 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
885 total_ms/1000, total_ms%1000,
886 wall_ms/1000, wall_ms%1000,
887 (mem_peak_kb + 1023) / 1024,
891 if (WIFSIGNALED(stat))
894 meta_printf("exitsig:%d\n", WTERMSIG(stat));
896 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
898 if (WIFSTOPPED(stat))
900 int sig = WSTOPSIG(stat);
904 static int stop_count = -1;
905 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
906 die("ptrace(PTRACE_GETREGS): %m");
907 if (u.regs.orig_eax < 0) /* Process issued a breakpoint instruction */
908 err("SG: Breakpoint");
910 if (!stop_count) /* Traceme request */
911 msg(">> Traceme request caught\n");
912 else if (stop_count & 1) /* Syscall entry */
916 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
920 if (u.regs.orig_eax == __NR_execve)
923 else if ((act = valid_syscall(&u)) >= 0)
926 if (act & A_SAMPLE_MEM)
932 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
933 * so we have to change it to something harmless (e.g., an undefined
934 * syscall) and make the program continue.
936 unsigned int sys = u.regs.orig_eax;
937 u.regs.orig_eax = 0xffffffff;
938 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
939 die("ptrace(PTRACE_SETREGS): %m");
940 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
943 else /* Syscall return */
944 msg("= %ld\n", u.regs.eax);
945 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
947 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
949 msg(">> Signal %d\n", sig);
950 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
951 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
955 meta_printf("exitsig:%d", sig);
956 err("SG: Received signal %d", sig);
960 die("wait4: unknown status %x, giving up!", stat);
965 box_inside(int argc, char **argv)
970 memcpy(args, argv, argc * sizeof(char *));
972 if (set_cwd && chdir(set_cwd))
977 if (open(redir_stdin, O_RDONLY) != 0)
978 die("open(\"%s\"): %m", redir_stdin);
983 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
984 die("open(\"%s\"): %m", redir_stdout);
989 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
990 die("open(\"%s\"): %m", redir_stderr);
997 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
998 if (setrlimit(RLIMIT_AS, &rl) < 0)
999 die("setrlimit: %m");
1001 rl.rlim_cur = rl.rlim_max = 64;
1002 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1003 die("setrlimit: %m");
1004 if (filter_syscalls)
1006 if (ptrace(PTRACE_TRACEME) < 0)
1007 die("ptrace(PTRACE_TRACEME): %m");
1008 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1009 signal(SIGCHLD, SIG_IGN);
1012 execve(args[0], args, setup_environment());
1013 die("execve(\"%s\"): %m", args[0]);
1019 fprintf(stderr, "Invalid arguments!\n");
1021 Usage: box [<options>] -- <command> <arguments>\n\
1024 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1025 -c <dir>\tChange directory to <dir> first\n\
1026 -e\t\tInherit full environment of the parent process\n\
1027 -E <var>\tInherit the environment variable <var> from the parent process\n\
1028 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1029 -f\t\tFilter system calls (-ff=very restricted)\n\
1030 -i <file>\tRedirect stdin from <file>\n\
1031 -m <size>\tLimit address space to <size> KB\n\
1032 -M <file>\tOutput process information to <file> (name:value)\n\
1033 -o <file>\tRedirect stdout to <file>\n\
1034 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1035 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1036 -r <file>\tRedirect stderr to <file>\n\
1037 -s <sys>\tPermit the specified syscall (be careful)\n\
1038 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1039 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1040 -T\t\tAllow syscalls for measuring run time\n\
1041 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1042 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1048 main(int argc, char **argv)
1053 while ((c = getopt(argc, argv, "a:c:eE:fi:m:M:o:p:r:s:t:Tvw:")) >= 0)
1057 file_access = atol(optarg);
1066 if (!set_env_action(optarg))
1073 redir_stdin = optarg;
1076 memory_limit = atol(optarg);
1082 redir_stdout = optarg;
1085 if (!set_path_action(optarg))
1089 redir_stderr = optarg;
1092 if (!set_syscall_action(optarg))
1096 timeout = 1000*atof(optarg);
1099 syscall_action[__NR_times] = A_YES;
1105 wall_timeout = 1000*atof(optarg);
1114 if (setreuid(uid, uid) < 0)
1115 die("setreuid: %m");
1120 box_inside(argc-optind, argv+optind);
1123 die("Internal error: fell over edge of the world");