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
214 A_LIBERAL = 128, // Valid only in liberal mode
217 static unsigned char syscall_action[NUM_ACTIONS] = {
218 #define S(x) [__NR_##x]
220 // Syscalls permitted for specific file names
221 S(open) = A_FILENAME,
222 S(creat) = A_FILENAME,
223 S(unlink) = A_FILENAME,
224 S(oldstat) = A_FILENAME,
225 S(access) = A_FILENAME,
226 S(oldlstat) = A_FILENAME,
227 S(truncate) = A_FILENAME,
228 S(stat) = A_FILENAME,
229 S(lstat) = A_FILENAME,
230 S(truncate64) = A_FILENAME,
231 S(stat64) = A_FILENAME,
232 S(lstat64) = A_FILENAME,
233 S(readlink) = A_FILENAME,
235 // Syscalls permitted always
250 S(ftruncate) = A_YES,
252 S(personality) = A_YES,
256 S(getresuid) = A_YES,
264 S(ftruncate64) = A_YES,
274 S(set_thread_area) = A_YES,
275 S(get_thread_area) = A_YES,
276 S(set_tid_address) = A_YES,
277 S(exit_group) = A_YES,
279 // Syscalls permitted only in liberal mode
280 S(time) = A_YES | A_LIBERAL,
281 S(alarm) = A_YES | A_LIBERAL,
282 S(pause) = A_YES | A_LIBERAL,
283 S(signal) = A_YES | A_LIBERAL,
284 S(fchmod) = A_YES | A_LIBERAL,
285 S(sigaction) = A_YES | A_LIBERAL,
286 S(sgetmask) = A_YES | A_LIBERAL,
287 S(ssetmask) = A_YES | A_LIBERAL,
288 S(sigsuspend) = A_YES | A_LIBERAL,
289 S(sigpending) = A_YES | A_LIBERAL,
290 S(getrlimit) = A_YES | A_LIBERAL,
291 S(getrusage) = A_YES | A_LIBERAL,
292 S(ugetrlimit) = A_YES | A_LIBERAL,
293 S(gettimeofday) = A_YES | A_LIBERAL,
294 S(select) = A_YES | A_LIBERAL,
295 S(readdir) = A_YES | A_LIBERAL,
296 S(setitimer) = A_YES | A_LIBERAL,
297 S(getitimer) = A_YES | A_LIBERAL,
298 S(sigreturn) = A_YES | A_LIBERAL,
299 S(mprotect) = A_YES | A_LIBERAL,
300 S(sigprocmask) = A_YES | A_LIBERAL,
301 S(getdents) = A_YES | A_LIBERAL,
302 S(getdents64) = A_YES | A_LIBERAL,
303 S(_newselect) = A_YES | A_LIBERAL,
304 S(fdatasync) = A_YES | A_LIBERAL,
305 S(mremap) = A_YES | A_LIBERAL,
306 S(poll) = A_YES | A_LIBERAL,
307 S(getcwd) = A_YES | A_LIBERAL,
308 S(nanosleep) = A_YES | A_LIBERAL,
309 S(rt_sigreturn) = A_YES | A_LIBERAL,
310 S(rt_sigaction) = A_YES | A_LIBERAL,
311 S(rt_sigprocmask) = A_YES | A_LIBERAL,
312 S(rt_sigpending) = A_YES | A_LIBERAL,
313 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
314 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
315 S(rt_sigsuspend) = A_YES | A_LIBERAL,
316 S(_sysctl) = A_YES | A_LIBERAL,
321 syscall_name(unsigned int id, char *buf)
323 if (id < NUM_SYSCALLS && syscall_names[id])
324 return syscall_names[id];
327 sprintf(buf, "#%d", id);
333 syscall_by_name(char *name)
335 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
336 if (syscall_names[i] && !strcmp(syscall_names[i], name))
343 unsigned long l = strtoul(name, &ep, 0);
346 if (l >= NUM_ACTIONS)
352 set_syscall_action(char *a)
354 char *sep = strchr(a, '=');
355 enum action act = A_YES;
359 if (!strcmp(sep, "yes"))
361 else if (!strcmp(sep, "no"))
363 else if (!strcmp(sep, "file"))
369 int sys = syscall_by_name(a);
371 die("Unknown syscall `%s'", a);
372 if (sys >= NUM_ACTIONS)
373 die("Syscall `%s' out of range", a);
374 syscall_action[sys] = act;
383 struct path_rule *next;
386 static struct path_rule default_path_rules[] = {
389 { "/usr/lib/", A_YES },
390 { "/opt/lib/", A_YES },
391 { "/usr/share/zoneinfo/", A_YES },
392 { "/usr/share/locale/", A_YES },
393 { "/dev/null", A_YES },
394 { "/dev/zero", A_YES },
395 { "/proc/meminfo", A_YES },
396 { "/proc/self/stat", A_YES },
397 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
400 static struct path_rule *user_path_rules;
401 static struct path_rule **last_path_rule = &user_path_rules;
404 set_path_action(char *a)
406 char *sep = strchr(a, '=');
407 enum action act = A_YES;
411 if (!strcmp(sep, "yes"))
413 else if (!strcmp(sep, "no"))
419 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
420 r->path = (char *)(r+1);
425 last_path_rule = &r->next;
430 match_path_rule(struct path_rule *r, char *path)
434 if (*rr++ != *path++)
436 if (rr[-1] == '/' && !path[-1])
440 if (rr > r->path && rr[-1] != '/' && *path)
445 /*** Environment rules ***/
448 char *var; // Variable to match
449 char *val; // ""=clear, NULL=inherit
451 struct env_rule *next;
454 static struct env_rule *first_env_rule;
455 static struct env_rule **last_env_rule = &first_env_rule;
457 static struct env_rule default_env_rules[] = {
458 { "LIBC_FATAL_STDERR_", "1" }
462 set_env_action(char *a0)
464 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
465 char *a = (char *)(r+1);
468 char *sep = strchr(a, '=');
480 last_env_rule = &r->next;
486 match_env_var(char *env_entry, struct env_rule *r)
488 if (strncmp(env_entry, r->var, r->var_len))
490 return (env_entry[r->var_len] == '=');
494 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
496 // First remove the variable if already set
498 while (pos < *env_sizep && !match_env_var(env[pos], r))
500 if (pos < *env_sizep)
503 env[pos] = env[*env_sizep];
504 env[*env_sizep] = NULL;
507 // What is the new value?
513 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
514 sprintf(new, "%s=%s", r->var, r->val);
519 while (environ[pos] && !match_env_var(environ[pos], r))
521 if (!(new = environ[pos]))
525 // Add it at the end of the array
526 env[(*env_sizep)++] = new;
527 env[*env_sizep] = NULL;
531 setup_environment(void)
533 // Link built-in rules with user rules
534 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
536 default_env_rules[i].next = first_env_rule;
537 first_env_rule = &default_env_rules[i];
540 // Scan the original environment
541 char **orig_env = environ;
543 while (orig_env[orig_size])
546 // For each rule, reserve one more slot and calculate length
548 for (struct env_rule *r = first_env_rule; r; r=r->next)
551 r->var_len = strlen(r->var);
554 // Create a new environment
555 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
559 memcpy(env, environ, orig_size * sizeof(char *));
566 // Apply the rules one by one
567 for (struct env_rule *r = first_env_rule; r; r=r->next)
568 apply_env_rule(env, &size, r);
570 // Return the new env and pass some gossip
573 fprintf(stderr, "Passing environment:\n");
574 for (int i=0; env[i]; i++)
575 fprintf(stderr, "\t%s\n", env[i]);
580 /*** Syscall checks ***/
583 valid_filename(unsigned long addr)
585 char namebuf[4096], *p, *end;
589 err("FA: File access forbidden");
590 if (file_access >= 9)
595 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
596 mem_fd = open(namebuf, O_RDONLY);
598 die("open(%s): %m", namebuf);
605 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
606 int l = namebuf + sizeof(namebuf) - end;
610 err("FA: Access to file with name too long");
611 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
612 die("lseek64(mem): %m");
613 remains = read(mem_fd, end, l);
615 die("read(mem): %m");
617 err("FA: Access to file with name out of memory");
624 msg("[%s] ", namebuf);
625 if (file_access >= 3)
628 // Everything in current directory is permitted
629 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
632 // ".." anywhere in the path is forbidden
633 enum action act = A_DEFAULT;
634 if (strstr(namebuf, ".."))
638 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
639 act = match_path_rule(r, namebuf);
641 // Scan built-in rules
642 if (file_access >= 2)
643 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
644 act = match_path_rule(&default_path_rules[i], namebuf);
647 err("FA: Forbidden access to file `%s'", namebuf);
651 valid_syscall(struct user *u)
653 unsigned int sys = u->regs.orig_eax;
654 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
658 if (filter_syscalls == 1)
670 valid_filename(u->regs.ebx);
678 if (u->regs.ebx == box_pid)
680 meta_printf("exitsig:%d\n", (int)u->regs.ecx);
681 err("SG: Committed suicide by signal %d", (int)u->regs.ecx);
685 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
687 meta_printf("exitsig:%d\n", (int)u->regs.edx);
688 err("SG: Committed suicide by signal %d", (int)u->regs.edx);
697 signal_alarm(int unused UNUSED)
699 /* Time limit checks are synchronous, so we only schedule them there. */
705 signal_int(int unused UNUSED)
707 /* Interrupts are fatal, so no synchronization requirements. */
708 meta_printf("exitsig:%d\n", SIGINT);
709 err("SG: Interrupted");
712 #define PROC_BUF_SIZE 4096
714 read_proc_file(char *buf, char *name, int *fdp)
720 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
721 *fdp = open(buf, O_RDONLY);
723 die("open(%s): %m", buf);
725 lseek(*fdp, 0, SEEK_SET);
726 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
727 die("read on /proc/$pid/%s: %m", name);
728 if (c >= PROC_BUF_SIZE-1)
729 die("/proc/$pid/%s too long", name);
738 struct timeval now, wall;
740 gettimeofday(&now, NULL);
741 timersub(&now, &start_time, &wall);
742 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
743 if (wall_ms > wall_timeout)
744 err("TO: Time limit exceeded (wall clock)");
746 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
750 char buf[PROC_BUF_SIZE], *x;
751 int utime, stime, ms;
752 static int proc_stat_fd;
753 read_proc_file(buf, "stat", &proc_stat_fd);
755 while (*x && *x != ' ')
760 die("proc stat syntax error 1");
761 while (*x && (*x != ')' || x[1] != ' '))
763 while (*x == ')' || *x == ' ')
765 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
766 die("proc stat syntax error 2");
767 ms = (utime + stime) * 1000 / ticks_per_sec;
769 fprintf(stderr, "[time check: %d msec]\n", ms);
771 err("TO: Time limit exceeded");
776 sample_mem_peak(void)
779 * We want to find out the peak memory usage of the process, which is
780 * maintained by the kernel, but unforunately it gets lost when the
781 * process exits (it is not reported in struct rusage). Therefore we
782 * have to sample it whenever we suspect that the process is about
785 char buf[PROC_BUF_SIZE], *x;
786 static int proc_status_fd;
787 read_proc_file(buf, "status", &proc_status_fd);
793 while (*x && *x != ':' && *x != '\n')
795 if (!*x || *x == '\n')
798 while (*x == ' ' || *x == '\t')
802 while (*x && *x != '\n')
808 if (!strcmp(key, "VmPeak"))
810 int peak = atoi(val);
811 if (peak > mem_peak_kb)
817 msg("[mem-peak: %u KB]\n", mem_peak_kb);
823 int syscall_count = 0;
827 bzero(&sa, sizeof(sa));
828 sa.sa_handler = signal_int;
829 sigaction(SIGINT, &sa, NULL);
830 gettimeofday(&start_time, NULL);
831 ticks_per_sec = sysconf(_SC_CLK_TCK);
832 if (ticks_per_sec <= 0)
833 die("Invalid ticks_per_sec!");
834 if (timeout || wall_timeout)
836 sa.sa_handler = signal_alarm;
837 sigaction(SIGALRM, &sa, NULL);
850 p = wait4(box_pid, &stat, WUNTRACED, &rus);
858 die("wait4: unknown pid %d exited!", p);
863 if (WEXITSTATUS(stat))
867 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
868 err("RE: Exited with error status %d", WEXITSTATUS(stat));
872 // Internal error happened inside the child process and it has been already reported.
876 if (timeout && total_ms > timeout)
877 err("TO: Time limit exceeded");
878 if (wall_timeout && wall_ms > wall_timeout)
879 err("TO: Time limit exceeded (wall clock)");
881 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
882 total_ms/1000, total_ms%1000,
883 wall_ms/1000, wall_ms%1000,
884 (mem_peak_kb + 1023) / 1024,
888 if (WIFSIGNALED(stat))
891 meta_printf("exitsig:%d\n", WTERMSIG(stat));
893 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
895 if (WIFSTOPPED(stat))
897 int sig = WSTOPSIG(stat);
901 static int stop_count = -1;
902 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
903 die("ptrace(PTRACE_GETREGS): %m");
905 if (!stop_count) /* Traceme request */
906 msg(">> Traceme request caught\n");
907 else if (stop_count & 1) /* Syscall entry */
910 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
914 if (u.regs.orig_eax == __NR_execve)
917 else if (valid_syscall(&u))
922 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
923 * so we have to change it to something harmless (e.g., an undefined
924 * syscall) and make the program continue.
926 unsigned int sys = u.regs.orig_eax;
927 u.regs.orig_eax = 0xffffffff;
928 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
929 die("ptrace(PTRACE_SETREGS): %m");
930 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
933 else /* Syscall return */
934 msg("= %ld\n", u.regs.eax);
936 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
938 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
940 msg(">> Signal %d\n", sig);
941 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
942 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
946 meta_printf("exitsig:%d", sig);
947 err("SG: Received signal %d", sig);
951 die("wait4: unknown status %x, giving up!", stat);
956 box_inside(int argc, char **argv)
961 memcpy(args, argv, argc * sizeof(char *));
963 if (set_cwd && chdir(set_cwd))
968 if (open(redir_stdin, O_RDONLY) != 0)
969 die("open(\"%s\"): %m", redir_stdin);
974 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
975 die("open(\"%s\"): %m", redir_stdout);
980 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
981 die("open(\"%s\"): %m", redir_stderr);
988 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
989 if (setrlimit(RLIMIT_AS, &rl) < 0)
990 die("setrlimit: %m");
992 rl.rlim_cur = rl.rlim_max = 64;
993 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
994 die("setrlimit: %m");
997 if (ptrace(PTRACE_TRACEME) < 0)
998 die("ptrace(PTRACE_TRACEME): %m");
999 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1000 signal(SIGCHLD, SIG_IGN);
1003 execve(args[0], args, setup_environment());
1004 die("execve(\"%s\"): %m", args[0]);
1010 fprintf(stderr, "Invalid arguments!\n");
1012 Usage: box [<options>] -- <command> <arguments>\n\
1015 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1016 -c <dir>\tChange directory to <dir> first\n\
1017 -e\t\tInherit full environment of the parent process\n\
1018 -E <var>\tInherit the environment variable <var> from the parent process\n\
1019 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1020 -f\t\tFilter system calls (-ff=very restricted)\n\
1021 -i <file>\tRedirect stdin from <file>\n\
1022 -m <size>\tLimit address space to <size> KB\n\
1023 -M <file>\tOutput process information to <file> (name:value)\n\
1024 -o <file>\tRedirect stdout to <file>\n\
1025 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1026 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1027 -r <file>\tRedirect stderr to <file>\n\
1028 -s <sys>\tPermit the specified syscall (be careful)\n\
1029 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1030 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1031 -T\t\tAllow syscalls for measuring run time\n\
1032 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1033 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1039 main(int argc, char **argv)
1044 while ((c = getopt(argc, argv, "a:c:eE:fi:m:M:o:p:r:s:t:Tvw:")) >= 0)
1048 file_access = atol(optarg);
1057 if (!set_env_action(optarg))
1064 redir_stdin = optarg;
1067 memory_limit = atol(optarg);
1073 redir_stdout = optarg;
1076 if (!set_path_action(optarg))
1080 redir_stderr = optarg;
1083 if (!set_syscall_action(optarg))
1087 timeout = 1000*atof(optarg);
1090 syscall_action[__NR_times] = A_YES;
1096 wall_timeout = 1000*atof(optarg);
1105 if (setreuid(uid, uid) < 0)
1106 die("setreuid: %m");
1111 box_inside(argc-optind, argv+optind);
1114 die("Internal error: fell over edge of the world");