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(gettimeofday) = SC_YES | SC_LIBERAL,
181 S(select) = SC_YES | SC_LIBERAL,
182 S(readdir) = SC_YES | SC_LIBERAL,
183 S(setitimer) = SC_YES | SC_LIBERAL,
184 S(getitimer) = SC_YES | SC_LIBERAL,
185 S(sigreturn) = SC_YES | SC_LIBERAL,
186 S(mprotect) = SC_YES | SC_LIBERAL,
187 S(sigprocmask) = SC_YES | SC_LIBERAL,
188 S(getdents) = SC_YES | SC_LIBERAL,
189 S(getdents64) = SC_YES | SC_LIBERAL,
190 S(_newselect) = SC_YES | SC_LIBERAL,
191 S(fdatasync) = SC_YES | SC_LIBERAL,
192 S(mremap) = SC_YES | SC_LIBERAL,
193 S(poll) = SC_YES | SC_LIBERAL,
194 S(getcwd) = SC_YES | SC_LIBERAL,
195 S(nanosleep) = SC_YES | SC_LIBERAL,
196 S(rt_sigreturn) = SC_YES | SC_LIBERAL,
197 S(rt_sigaction) = SC_YES | SC_LIBERAL,
198 S(rt_sigprocmask) = SC_YES | SC_LIBERAL,
199 S(rt_sigpending) = SC_YES | SC_LIBERAL,
200 S(rt_sigtimedwait) = SC_YES | SC_LIBERAL,
201 S(rt_sigqueueinfo) = SC_YES | SC_LIBERAL,
202 S(rt_sigsuspend) = SC_YES | SC_LIBERAL,
203 S(mmap2) = SC_YES | SC_LIBERAL,
204 S(_sysctl) = SC_YES | SC_LIBERAL,
209 syscall_name(unsigned int id, char *buf)
211 if (id < NUM_SYSCALLS && syscall_tab[id])
212 return syscall_tab[id];
215 sprintf(buf, "#%d", id);
221 syscall_by_name(char *name)
223 for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
224 if (!strcmp(syscall_tab[i], name))
230 valid_filename(unsigned long addr)
232 char namebuf[4096], *p, *end;
236 die("File access forbidden");
237 if (file_access >= 9)
242 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
243 mem_fd = open(namebuf, O_RDONLY);
245 die("open(%s): %m", namebuf);
252 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
253 int l = namebuf + sizeof(namebuf) - end;
257 die("Access to file with name too long");
258 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
259 die("long_seek(mem): %m");
260 remains = read(mem_fd, end, l);
262 die("read(mem): %m");
264 die("Access to file with name out of memory");
271 msg("[%s] ", namebuf);
272 if (file_access >= 3)
274 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
276 if (file_access >= 2)
278 if ((!strncmp(namebuf, "/etc/", 5) ||
279 !strncmp(namebuf, "/lib/", 5) ||
280 !strncmp(namebuf, "/usr/lib/", 9) ||
281 !strncmp(namebuf, "/opt/lib/", 9))
282 && !strstr(namebuf, ".."))
284 if (!strcmp(namebuf, "/dev/null") ||
285 !strcmp(namebuf, "/dev/zero") ||
286 !strcmp(namebuf, "/proc/meminfo") ||
287 !strcmp(namebuf, "/proc/self/stat") ||
288 !strcmp(namebuf, "/proc/self/exe") || /* Needed by FPC 2.0.x runtime */
289 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
292 die("Forbidden access to file `%s'", namebuf);
296 valid_syscall(struct user *u)
298 unsigned int sys = u->regs.orig_eax;
299 enum syscall_action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
301 if (act & SC_LIBERAL)
303 if (filter_syscalls == 1)
315 valid_filename(u->regs.ebx);
323 if (u->regs.ebx == box_pid)
324 die("Committed suicide by signal %d", (int)u->regs.ecx);
327 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
328 die("Committed suicide by signal %d", (int)u->regs.edx);
336 signal_alarm(int unused UNUSED)
338 /* Time limit checks are synchronous, so we only schedule them there. */
344 signal_int(int unused UNUSED)
346 /* Interrupts are fatal, so no synchronization requirements. */
355 struct timeval now, wall;
357 gettimeofday(&now, NULL);
358 timersub(&now, &start_time, &wall);
359 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
360 if (wall_ms > wall_timeout)
361 die("Time limit exceeded (wall clock)");
363 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
368 int c, utime, stime, ms;
369 static int proc_status_fd;
372 sprintf(buf, "/proc/%d/stat", (int) box_pid);
373 proc_status_fd = open(buf, O_RDONLY);
374 if (proc_status_fd < 0)
375 die("open(%s): %m", buf);
377 lseek(proc_status_fd, 0, SEEK_SET);
378 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
379 die("read on /proc/$pid/stat: %m");
380 if (c >= (int) sizeof(buf) - 1)
381 die("/proc/$pid/stat too long");
384 while (*x && *x != ' ')
389 die("proc syntax error 1");
390 while (*x && (*x != ')' || x[1] != ' '))
392 while (*x == ')' || *x == ' ')
394 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
395 die("proc syntax error 2");
396 ms = (utime + stime) * 1000 / ticks_per_sec;
398 fprintf(stderr, "[time check: %d msec]\n", ms);
400 die("Time limit exceeded");
407 int syscall_count = 0;
411 bzero(&sa, sizeof(sa));
412 sa.sa_handler = signal_int;
413 sigaction(SIGINT, &sa, NULL);
414 gettimeofday(&start_time, NULL);
415 ticks_per_sec = sysconf(_SC_CLK_TCK);
416 if (ticks_per_sec <= 0)
417 die("Invalid ticks_per_sec!");
418 if (timeout || wall_timeout)
420 sa.sa_handler = signal_alarm;
421 sigaction(SIGALRM, &sa, NULL);
434 p = wait4(box_pid, &stat, WUNTRACED, &rus);
442 die("wait4: unknown pid %d exited!", p);
445 struct timeval total, now, wall;
446 int total_ms, wall_ms;
448 if (WEXITSTATUS(stat))
449 die("Exited with error status %d", WEXITSTATUS(stat));
450 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
451 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
452 gettimeofday(&now, NULL);
453 timersub(&now, &start_time, &wall);
454 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
455 if (timeout && total_ms > timeout)
456 die("Time limit exceeded");
457 if (wall_timeout && wall_ms > wall_timeout)
458 die("Time limit exceeded (wall clock)");
459 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
460 (int) total.tv_sec, (int) total.tv_usec/1000,
461 (int) wall.tv_sec, (int) wall.tv_usec/1000,
465 if (WIFSIGNALED(stat))
468 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
470 if (WIFSTOPPED(stat))
472 int sig = WSTOPSIG(stat);
476 static int stop_count = -1;
477 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
478 die("ptrace(PTRACE_GETREGS): %m");
480 if (!stop_count) /* Traceme request */
481 msg(">> Traceme request caught\n");
482 else if (stop_count & 1) /* Syscall entry */
485 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
489 if (u.regs.orig_eax == __NR_execve)
492 else if (valid_syscall(&u))
497 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
498 * so we have to change it to something harmless (e.g., an undefined
499 * syscall) and make the program continue.
501 unsigned int sys = u.regs.orig_eax;
502 u.regs.orig_eax = 0xffffffff;
503 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
504 die("ptrace(PTRACE_SETREGS): %m");
505 die("Forbidden syscall %s", syscall_name(sys, namebuf));
508 else /* Syscall return */
509 msg("= %ld\n", u.regs.eax);
510 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
512 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
514 msg(">> Signal %d\n", sig);
515 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
518 die("Received signal %d", sig);
521 die("wait4: unknown status %x, giving up!", stat);
526 box_inside(int argc, char **argv)
530 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
532 memcpy(args, argv, argc * sizeof(char *));
534 if (set_cwd && chdir(set_cwd))
539 if (open(redir_stdin, O_RDONLY) != 0)
540 die("open(\"%s\"): %m", redir_stdin);
545 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
546 die("open(\"%s\"): %m", redir_stdout);
552 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
553 if (setrlimit(RLIMIT_AS, &rl) < 0)
554 die("setrlimit: %m");
556 rl.rlim_cur = rl.rlim_max = 64;
557 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
558 die("setrlimit: %m");
561 if (ptrace(PTRACE_TRACEME) < 0)
562 die("ptrace(PTRACE_TRACEME): %m");
563 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
564 signal(SIGCHLD, SIG_IGN);
567 execve(args[0], args, (pass_environ ? environ : env));
568 die("execve(\"%s\"): %m", args[0]);
574 fprintf(stderr, "Invalid arguments!\n");
576 Usage: box [<options>] -- <command> <arguments>\n\
579 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
580 -c <dir>\tChange directory to <dir> first\n\
581 -e\t\tPass full environment of parent process\n\
582 -f\t\tFilter system calls (-ff=very restricted)\n\
583 -i <file>\tRedirect stdin from <file>\n\
584 -m <size>\tLimit address space to <size> KB\n\
585 -o <file>\tRedirect stdout to <file>\n\
586 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
587 -T\t\tAllow syscalls for measuring run time\n\
589 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
595 main(int argc, char **argv)
600 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw:")) >= 0)
604 file_access = atol(optarg);
616 redir_stdin = optarg;
619 memory_limit = atol(optarg);
622 redir_stdout = optarg;
625 timeout = 1000*atof(optarg);
628 syscall_action[__NR_times] = SC_YES;
634 wall_timeout = 1000*atof(optarg);
643 if (setreuid(uid, uid) < 0)
649 box_inside(argc-optind, argv+optind);
652 die("Internal error: fell over edge of the world");