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))
31 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
32 static int timeout; /* milliseconds */
33 static int wall_timeout;
34 static int pass_environ;
35 static int file_access;
37 static int memory_limit;
38 static char *redir_stdin, *redir_stdout;
42 static int is_ptraced;
43 static volatile int timer_tick;
44 static struct timeval start_time;
45 static int ticks_per_sec;
48 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
49 /* glibc 2.1 or newer -> has lseek64 */
50 #define long_seek(f,o,w) lseek64(f,o,w)
52 /* Touching clandestine places in glibc */
53 extern loff_t llseek(int fd, loff_t pos, int whence);
54 #define long_seek(f,o,w) llseek(f,o,w)
63 ptrace(PTRACE_KILL, box_pid);
64 kill(-box_pid, SIGKILL);
65 kill(box_pid, SIGKILL);
70 static void NONRET __attribute__((format(printf,1,2)))
75 vfprintf(stderr, msg, args);
80 static void __attribute__((format(printf,1,2)))
87 vfprintf(stderr, msg, args);
93 static const char * const syscall_tab[] = {
94 #include "syscall-table.h"
96 #define NUM_SYSCALLS (sizeof(syscall_tab)/sizeof(syscall_tab[0]))
97 #define NUM_ACTIONS (NUM_SYSCALLS+64)
100 SC_DEFAULT, // Use the default action
101 SC_NO, // Always forbid
102 SC_YES, // Always permit
103 SC_FILENAME, // Permit if arg1 is a known filename
104 SC_LIBERAL = 128, // Valid only in liberal mode
107 static unsigned char syscall_action[NUM_ACTIONS] = {
108 #define S(x) [__NR_##x]
110 // Syscalls permitted for specific file names
111 S(open) = SC_FILENAME,
112 S(creat) = SC_FILENAME,
113 S(unlink) = SC_FILENAME,
114 S(oldstat) = SC_FILENAME,
115 S(access) = SC_FILENAME,
116 S(oldlstat) = SC_FILENAME,
117 S(truncate) = SC_FILENAME,
118 S(stat) = SC_FILENAME,
119 S(lstat) = SC_FILENAME,
120 S(truncate64) = SC_FILENAME,
121 S(stat64) = SC_FILENAME,
122 S(lstat64) = SC_FILENAME,
123 S(readlink) = SC_FILENAME,
125 // Syscalls permitted always
133 S(oldfstat) = SC_YES,
140 S(ftruncate) = SC_YES,
142 S(personality) = SC_YES,
146 S(getresuid) = SC_YES,
149 S(pwrite64) = SC_YES,
154 S(ftruncate64) = SC_YES,
163 S(set_thread_area) = SC_YES,
164 S(get_thread_area) = SC_YES,
165 S(exit_group) = SC_YES,
167 // Syscalls permitted only in liberal mode
168 S(time) = SC_YES | SC_LIBERAL,
169 S(alarm) = SC_YES | SC_LIBERAL,
170 S(pause) = SC_YES | SC_LIBERAL,
171 S(signal) = SC_YES | SC_LIBERAL,
172 S(fchmod) = SC_YES | SC_LIBERAL,
173 S(sigaction) = SC_YES | SC_LIBERAL,
174 S(sgetmask) = SC_YES | SC_LIBERAL,
175 S(ssetmask) = SC_YES | SC_LIBERAL,
176 S(sigsuspend) = SC_YES | SC_LIBERAL,
177 S(sigpending) = SC_YES | SC_LIBERAL,
178 S(getrlimit) = SC_YES | SC_LIBERAL,
179 S(getrusage) = SC_YES | SC_LIBERAL,
180 S(ugetrlimit) = SC_YES | SC_LIBERAL,
181 S(gettimeofday) = SC_YES | SC_LIBERAL,
182 S(select) = SC_YES | SC_LIBERAL,
183 S(readdir) = SC_YES | SC_LIBERAL,
184 S(setitimer) = SC_YES | SC_LIBERAL,
185 S(getitimer) = SC_YES | SC_LIBERAL,
186 S(sigreturn) = SC_YES | SC_LIBERAL,
187 S(mprotect) = SC_YES | SC_LIBERAL,
188 S(sigprocmask) = SC_YES | SC_LIBERAL,
189 S(getdents) = SC_YES | SC_LIBERAL,
190 S(getdents64) = SC_YES | SC_LIBERAL,
191 S(_newselect) = SC_YES | SC_LIBERAL,
192 S(fdatasync) = SC_YES | SC_LIBERAL,
193 S(mremap) = SC_YES | SC_LIBERAL,
194 S(poll) = SC_YES | SC_LIBERAL,
195 S(getcwd) = SC_YES | SC_LIBERAL,
196 S(nanosleep) = SC_YES | SC_LIBERAL,
197 S(rt_sigreturn) = SC_YES | SC_LIBERAL,
198 S(rt_sigaction) = SC_YES | SC_LIBERAL,
199 S(rt_sigprocmask) = SC_YES | SC_LIBERAL,
200 S(rt_sigpending) = SC_YES | SC_LIBERAL,
201 S(rt_sigtimedwait) = SC_YES | SC_LIBERAL,
202 S(rt_sigqueueinfo) = SC_YES | SC_LIBERAL,
203 S(rt_sigsuspend) = SC_YES | SC_LIBERAL,
204 S(mmap2) = SC_YES | SC_LIBERAL,
205 S(_sysctl) = SC_YES | SC_LIBERAL,
210 syscall_name(unsigned int id, char *buf)
212 if (id < NUM_SYSCALLS && syscall_tab[id])
213 return syscall_tab[id];
216 sprintf(buf, "#%d", id);
222 syscall_by_name(char *name)
224 for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
225 if (syscall_tab[i] && !strcmp(syscall_tab[i], name))
232 unsigned long l = strtoul(name, &ep, 0);
235 if (l >= NUM_ACTIONS)
243 char *sep = strchr(a, '=');
244 enum syscall_action act = SC_YES;
248 if (!strcmp(sep, "yes"))
250 else if (!strcmp(sep, "no"))
252 else if (!strcmp(sep, "file"))
258 int sys = syscall_by_name(a);
260 die("Unknown syscall `%s'", a);
261 if (sys >= (int)NUM_ACTIONS)
262 die("Syscall `%s' out of range", a);
263 syscall_action[sys] = act;
268 valid_filename(unsigned long addr)
270 char namebuf[4096], *p, *end;
274 die("File access forbidden");
275 if (file_access >= 9)
280 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
281 mem_fd = open(namebuf, O_RDONLY);
283 die("open(%s): %m", namebuf);
290 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
291 int l = namebuf + sizeof(namebuf) - end;
295 die("Access to file with name too long");
296 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
297 die("long_seek(mem): %m");
298 remains = read(mem_fd, end, l);
300 die("read(mem): %m");
302 die("Access to file with name out of memory");
309 msg("[%s] ", namebuf);
310 if (file_access >= 3)
312 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
314 if (file_access >= 2)
316 if ((!strncmp(namebuf, "/etc/", 5) ||
317 !strncmp(namebuf, "/lib/", 5) ||
318 !strncmp(namebuf, "/usr/lib/", 9) ||
319 !strncmp(namebuf, "/opt/lib/", 9))
320 && !strstr(namebuf, ".."))
322 if (!strcmp(namebuf, "/dev/null") ||
323 !strcmp(namebuf, "/dev/zero") ||
324 !strcmp(namebuf, "/proc/meminfo") ||
325 !strcmp(namebuf, "/proc/self/stat") ||
326 !strcmp(namebuf, "/proc/self/exe") || /* Needed by FPC 2.0.x runtime */
327 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
330 die("Forbidden access to file `%s'", namebuf);
334 valid_syscall(struct user *u)
336 unsigned int sys = u->regs.orig_eax;
337 enum syscall_action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
339 if (act & SC_LIBERAL)
341 if (filter_syscalls == 1)
353 valid_filename(u->regs.ebx);
361 if (u->regs.ebx == box_pid)
362 die("Committed suicide by signal %d", (int)u->regs.ecx);
365 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
366 die("Committed suicide by signal %d", (int)u->regs.edx);
374 signal_alarm(int unused UNUSED)
376 /* Time limit checks are synchronous, so we only schedule them there. */
382 signal_int(int unused UNUSED)
384 /* Interrupts are fatal, so no synchronization requirements. */
393 struct timeval now, wall;
395 gettimeofday(&now, NULL);
396 timersub(&now, &start_time, &wall);
397 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
398 if (wall_ms > wall_timeout)
399 die("Time limit exceeded (wall clock)");
401 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
406 int c, utime, stime, ms;
407 static int proc_status_fd;
410 sprintf(buf, "/proc/%d/stat", (int) box_pid);
411 proc_status_fd = open(buf, O_RDONLY);
412 if (proc_status_fd < 0)
413 die("open(%s): %m", buf);
415 lseek(proc_status_fd, 0, SEEK_SET);
416 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
417 die("read on /proc/$pid/stat: %m");
418 if (c >= (int) sizeof(buf) - 1)
419 die("/proc/$pid/stat too long");
422 while (*x && *x != ' ')
427 die("proc syntax error 1");
428 while (*x && (*x != ')' || x[1] != ' '))
430 while (*x == ')' || *x == ' ')
432 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
433 die("proc syntax error 2");
434 ms = (utime + stime) * 1000 / ticks_per_sec;
436 fprintf(stderr, "[time check: %d msec]\n", ms);
438 die("Time limit exceeded");
445 int syscall_count = 0;
449 bzero(&sa, sizeof(sa));
450 sa.sa_handler = signal_int;
451 sigaction(SIGINT, &sa, NULL);
452 gettimeofday(&start_time, NULL);
453 ticks_per_sec = sysconf(_SC_CLK_TCK);
454 if (ticks_per_sec <= 0)
455 die("Invalid ticks_per_sec!");
456 if (timeout || wall_timeout)
458 sa.sa_handler = signal_alarm;
459 sigaction(SIGALRM, &sa, NULL);
472 p = wait4(box_pid, &stat, WUNTRACED, &rus);
480 die("wait4: unknown pid %d exited!", p);
483 struct timeval total, now, wall;
484 int total_ms, wall_ms;
486 if (WEXITSTATUS(stat))
487 die("Exited with error status %d", WEXITSTATUS(stat));
488 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
489 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
490 gettimeofday(&now, NULL);
491 timersub(&now, &start_time, &wall);
492 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
493 if (timeout && total_ms > timeout)
494 die("Time limit exceeded");
495 if (wall_timeout && wall_ms > wall_timeout)
496 die("Time limit exceeded (wall clock)");
497 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
498 (int) total.tv_sec, (int) total.tv_usec/1000,
499 (int) wall.tv_sec, (int) wall.tv_usec/1000,
503 if (WIFSIGNALED(stat))
506 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
508 if (WIFSTOPPED(stat))
510 int sig = WSTOPSIG(stat);
514 static int stop_count = -1;
515 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
516 die("ptrace(PTRACE_GETREGS): %m");
518 if (!stop_count) /* Traceme request */
519 msg(">> Traceme request caught\n");
520 else if (stop_count & 1) /* Syscall entry */
523 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
527 if (u.regs.orig_eax == __NR_execve)
530 else if (valid_syscall(&u))
535 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
536 * so we have to change it to something harmless (e.g., an undefined
537 * syscall) and make the program continue.
539 unsigned int sys = u.regs.orig_eax;
540 u.regs.orig_eax = 0xffffffff;
541 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
542 die("ptrace(PTRACE_SETREGS): %m");
543 die("Forbidden syscall %s", syscall_name(sys, namebuf));
546 else /* Syscall return */
547 msg("= %ld\n", u.regs.eax);
548 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
550 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
552 msg(">> Signal %d\n", sig);
553 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
556 die("Received signal %d", sig);
559 die("wait4: unknown status %x, giving up!", stat);
564 box_inside(int argc, char **argv)
568 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
570 memcpy(args, argv, argc * sizeof(char *));
572 if (set_cwd && chdir(set_cwd))
577 if (open(redir_stdin, O_RDONLY) != 0)
578 die("open(\"%s\"): %m", redir_stdin);
583 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
584 die("open(\"%s\"): %m", redir_stdout);
590 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
591 if (setrlimit(RLIMIT_AS, &rl) < 0)
592 die("setrlimit: %m");
594 rl.rlim_cur = rl.rlim_max = 64;
595 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
596 die("setrlimit: %m");
599 if (ptrace(PTRACE_TRACEME) < 0)
600 die("ptrace(PTRACE_TRACEME): %m");
601 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
602 signal(SIGCHLD, SIG_IGN);
605 execve(args[0], args, (pass_environ ? environ : env));
606 die("execve(\"%s\"): %m", args[0]);
612 fprintf(stderr, "Invalid arguments!\n");
614 Usage: box [<options>] -- <command> <arguments>\n\
617 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
618 -c <dir>\tChange directory to <dir> first\n\
619 -e\t\tPass full environment of parent process\n\
620 -f\t\tFilter system calls (-ff=very restricted)\n\
621 -i <file>\tRedirect stdin from <file>\n\
622 -m <size>\tLimit address space to <size> KB\n\
623 -o <file>\tRedirect stdout to <file>\n\
624 -s <sys>\tPermit the specified syscall (be careful)\n\
625 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
626 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
627 -T\t\tAllow syscalls for measuring run time\n\
629 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
635 main(int argc, char **argv)
640 while ((c = getopt(argc, argv, "a:c:efi:m:o:s:t:Tvw:")) >= 0)
644 file_access = atol(optarg);
656 redir_stdin = optarg;
659 memory_limit = atol(optarg);
662 redir_stdout = optarg;
665 if (!set_action(optarg))
669 timeout = 1000*atof(optarg);
672 syscall_action[__NR_times] = SC_YES;
678 wall_timeout = 1000*atof(optarg);
687 if (setreuid(uid, uid) < 0)
693 box_inside(argc-optind, argv+optind);
696 die("Internal error: fell over edge of the world");