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;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static struct timeval start_time;
46 static int ticks_per_sec;
49 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
50 /* glibc 2.1 or newer -> has lseek64 */
51 #define long_seek(f,o,w) lseek64(f,o,w)
53 /* Touching clandestine places in glibc */
54 extern loff_t llseek(int fd, loff_t pos, int whence);
55 #define long_seek(f,o,w) llseek(f,o,w)
64 ptrace(PTRACE_KILL, box_pid);
65 kill(-box_pid, SIGKILL);
66 kill(box_pid, SIGKILL);
71 static void NONRET __attribute__((format(printf,1,2)))
76 vfprintf(stderr, msg, args);
81 static void __attribute__((format(printf,1,2)))
88 vfprintf(stderr, msg, args);
94 static const char * const syscall_tab[] = {
95 #include "syscall-table.h"
97 #define NUM_SYSCALLS (sizeof(syscall_tab)/sizeof(syscall_tab[0]))
98 #define NUM_ACTIONS (NUM_SYSCALLS+64)
101 SC_DEFAULT, // Use the default action
102 SC_NO, // Always forbid
103 SC_YES, // Always permit
104 SC_FILENAME, // Permit if arg1 is a known filename
105 SC_LIBERAL = 128, // Valid only in liberal mode
108 static unsigned char syscall_action[NUM_ACTIONS] = {
109 #define S(x) [__NR_##x]
111 // Syscalls permitted for specific file names
112 S(open) = SC_FILENAME,
113 S(creat) = SC_FILENAME,
114 S(unlink) = SC_FILENAME,
115 S(oldstat) = SC_FILENAME,
116 S(access) = SC_FILENAME,
117 S(oldlstat) = SC_FILENAME,
118 S(truncate) = SC_FILENAME,
119 S(stat) = SC_FILENAME,
120 S(lstat) = SC_FILENAME,
121 S(truncate64) = SC_FILENAME,
122 S(stat64) = SC_FILENAME,
123 S(lstat64) = SC_FILENAME,
124 S(readlink) = SC_FILENAME,
126 // Syscalls permitted always
134 S(oldfstat) = SC_YES,
141 S(ftruncate) = SC_YES,
143 S(personality) = SC_YES,
147 S(getresuid) = SC_YES,
150 S(pwrite64) = SC_YES,
155 S(ftruncate64) = SC_YES,
164 S(set_thread_area) = SC_YES,
165 S(get_thread_area) = SC_YES,
166 S(exit_group) = SC_YES,
168 // Syscalls permitted only in liberal mode
169 S(time) = SC_YES | SC_LIBERAL,
170 S(alarm) = SC_YES | SC_LIBERAL,
171 S(pause) = SC_YES | SC_LIBERAL,
172 S(signal) = SC_YES | SC_LIBERAL,
173 S(fchmod) = SC_YES | SC_LIBERAL,
174 S(sigaction) = SC_YES | SC_LIBERAL,
175 S(sgetmask) = SC_YES | SC_LIBERAL,
176 S(ssetmask) = SC_YES | SC_LIBERAL,
177 S(sigsuspend) = SC_YES | SC_LIBERAL,
178 S(sigpending) = SC_YES | SC_LIBERAL,
179 S(getrlimit) = SC_YES | SC_LIBERAL,
180 S(getrusage) = SC_YES | SC_LIBERAL,
181 S(ugetrlimit) = SC_YES | SC_LIBERAL,
182 S(gettimeofday) = SC_YES | SC_LIBERAL,
183 S(select) = SC_YES | SC_LIBERAL,
184 S(readdir) = SC_YES | SC_LIBERAL,
185 S(setitimer) = SC_YES | SC_LIBERAL,
186 S(getitimer) = SC_YES | SC_LIBERAL,
187 S(sigreturn) = SC_YES | SC_LIBERAL,
188 S(mprotect) = SC_YES | SC_LIBERAL,
189 S(sigprocmask) = SC_YES | SC_LIBERAL,
190 S(getdents) = SC_YES | SC_LIBERAL,
191 S(getdents64) = SC_YES | SC_LIBERAL,
192 S(_newselect) = SC_YES | SC_LIBERAL,
193 S(fdatasync) = SC_YES | SC_LIBERAL,
194 S(mremap) = SC_YES | SC_LIBERAL,
195 S(poll) = SC_YES | SC_LIBERAL,
196 S(getcwd) = SC_YES | SC_LIBERAL,
197 S(nanosleep) = SC_YES | SC_LIBERAL,
198 S(rt_sigreturn) = SC_YES | SC_LIBERAL,
199 S(rt_sigaction) = SC_YES | SC_LIBERAL,
200 S(rt_sigprocmask) = SC_YES | SC_LIBERAL,
201 S(rt_sigpending) = SC_YES | SC_LIBERAL,
202 S(rt_sigtimedwait) = SC_YES | SC_LIBERAL,
203 S(rt_sigqueueinfo) = SC_YES | SC_LIBERAL,
204 S(rt_sigsuspend) = SC_YES | SC_LIBERAL,
205 S(mmap2) = SC_YES | SC_LIBERAL,
206 S(_sysctl) = SC_YES | SC_LIBERAL,
211 syscall_name(unsigned int id, char *buf)
213 if (id < NUM_SYSCALLS && syscall_tab[id])
214 return syscall_tab[id];
217 sprintf(buf, "#%d", id);
223 syscall_by_name(char *name)
225 for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
226 if (syscall_tab[i] && !strcmp(syscall_tab[i], name))
233 unsigned long l = strtoul(name, &ep, 0);
236 if (l >= NUM_ACTIONS)
244 char *sep = strchr(a, '=');
245 enum action act = SC_YES;
249 if (!strcmp(sep, "yes"))
251 else if (!strcmp(sep, "no"))
253 else if (!strcmp(sep, "file"))
259 int sys = syscall_by_name(a);
261 die("Unknown syscall `%s'", a);
262 if (sys >= (int)NUM_ACTIONS)
263 die("Syscall `%s' out of range", a);
264 syscall_action[sys] = act;
271 struct path_rule *next;
274 static struct path_rule default_path_rules[] = {
277 { "/usr/lib/", SC_YES },
278 { "/opt/lib/", SC_YES },
279 { "/usr/share/zoneinfo/", SC_YES },
280 { "/dev/null", SC_YES },
281 { "/dev/zero", SC_YES },
282 { "/proc/meminfo", SC_YES },
283 { "/proc/self/stat", SC_YES },
284 { "/proc/self/exe", SC_YES }, // Needed by FPC 2.0.x runtime
288 match_path_rule(struct path_rule *r, char *path)
292 if (*rr++ != *path++)
294 if (rr[-1] == '/' && !path[-1])
298 if (rr > r->path && rr[-1] != '/' && *path)
304 valid_filename(unsigned long addr)
306 char namebuf[4096], *p, *end;
310 die("File access forbidden");
311 if (file_access >= 9)
316 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
317 mem_fd = open(namebuf, O_RDONLY);
319 die("open(%s): %m", namebuf);
326 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
327 int l = namebuf + sizeof(namebuf) - end;
331 die("Access to file with name too long");
332 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
333 die("long_seek(mem): %m");
334 remains = read(mem_fd, end, l);
336 die("read(mem): %m");
338 die("Access to file with name out of memory");
345 msg("[%s] ", namebuf);
346 if (file_access >= 3)
349 // Everything in current directory is permitted
350 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
353 // ".." anywhere in the path is forbidden
354 enum action act = SC_DEFAULT;
355 if (strstr(namebuf, ".."))
358 // Scan built-in rules
359 if (file_access >= 2)
360 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
361 act = match_path_rule(&default_path_rules[i], namebuf);
364 die("Forbidden access to file `%s'", namebuf);
368 valid_syscall(struct user *u)
370 unsigned int sys = u->regs.orig_eax;
371 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
373 if (act & SC_LIBERAL)
375 if (filter_syscalls == 1)
387 valid_filename(u->regs.ebx);
395 if (u->regs.ebx == box_pid)
396 die("Committed suicide by signal %d", (int)u->regs.ecx);
399 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
400 die("Committed suicide by signal %d", (int)u->regs.edx);
408 signal_alarm(int unused UNUSED)
410 /* Time limit checks are synchronous, so we only schedule them there. */
416 signal_int(int unused UNUSED)
418 /* Interrupts are fatal, so no synchronization requirements. */
427 struct timeval now, wall;
429 gettimeofday(&now, NULL);
430 timersub(&now, &start_time, &wall);
431 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
432 if (wall_ms > wall_timeout)
433 die("Time limit exceeded (wall clock)");
435 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
440 int c, utime, stime, ms;
441 static int proc_status_fd;
444 sprintf(buf, "/proc/%d/stat", (int) box_pid);
445 proc_status_fd = open(buf, O_RDONLY);
446 if (proc_status_fd < 0)
447 die("open(%s): %m", buf);
449 lseek(proc_status_fd, 0, SEEK_SET);
450 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
451 die("read on /proc/$pid/stat: %m");
452 if (c >= (int) sizeof(buf) - 1)
453 die("/proc/$pid/stat too long");
456 while (*x && *x != ' ')
461 die("proc syntax error 1");
462 while (*x && (*x != ')' || x[1] != ' '))
464 while (*x == ')' || *x == ' ')
466 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
467 die("proc syntax error 2");
468 ms = (utime + stime) * 1000 / ticks_per_sec;
470 fprintf(stderr, "[time check: %d msec]\n", ms);
472 die("Time limit exceeded");
479 int syscall_count = 0;
483 bzero(&sa, sizeof(sa));
484 sa.sa_handler = signal_int;
485 sigaction(SIGINT, &sa, NULL);
486 gettimeofday(&start_time, NULL);
487 ticks_per_sec = sysconf(_SC_CLK_TCK);
488 if (ticks_per_sec <= 0)
489 die("Invalid ticks_per_sec!");
490 if (timeout || wall_timeout)
492 sa.sa_handler = signal_alarm;
493 sigaction(SIGALRM, &sa, NULL);
506 p = wait4(box_pid, &stat, WUNTRACED, &rus);
514 die("wait4: unknown pid %d exited!", p);
517 struct timeval total, now, wall;
518 int total_ms, wall_ms;
520 if (WEXITSTATUS(stat))
521 die("Exited with error status %d", WEXITSTATUS(stat));
522 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
523 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
524 gettimeofday(&now, NULL);
525 timersub(&now, &start_time, &wall);
526 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
527 if (timeout && total_ms > timeout)
528 die("Time limit exceeded");
529 if (wall_timeout && wall_ms > wall_timeout)
530 die("Time limit exceeded (wall clock)");
531 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
532 (int) total.tv_sec, (int) total.tv_usec/1000,
533 (int) wall.tv_sec, (int) wall.tv_usec/1000,
537 if (WIFSIGNALED(stat))
540 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
542 if (WIFSTOPPED(stat))
544 int sig = WSTOPSIG(stat);
548 static int stop_count = -1;
549 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
550 die("ptrace(PTRACE_GETREGS): %m");
552 if (!stop_count) /* Traceme request */
553 msg(">> Traceme request caught\n");
554 else if (stop_count & 1) /* Syscall entry */
557 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
561 if (u.regs.orig_eax == __NR_execve)
564 else if (valid_syscall(&u))
569 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
570 * so we have to change it to something harmless (e.g., an undefined
571 * syscall) and make the program continue.
573 unsigned int sys = u.regs.orig_eax;
574 u.regs.orig_eax = 0xffffffff;
575 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
576 die("ptrace(PTRACE_SETREGS): %m");
577 die("Forbidden syscall %s", syscall_name(sys, namebuf));
580 else /* Syscall return */
581 msg("= %ld\n", u.regs.eax);
582 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
584 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
586 msg(">> Signal %d\n", sig);
587 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
590 die("Received signal %d", sig);
593 die("wait4: unknown status %x, giving up!", stat);
598 box_inside(int argc, char **argv)
602 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
604 memcpy(args, argv, argc * sizeof(char *));
606 if (set_cwd && chdir(set_cwd))
611 if (open(redir_stdin, O_RDONLY) != 0)
612 die("open(\"%s\"): %m", redir_stdin);
617 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
618 die("open(\"%s\"): %m", redir_stdout);
624 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
625 if (setrlimit(RLIMIT_AS, &rl) < 0)
626 die("setrlimit: %m");
628 rl.rlim_cur = rl.rlim_max = 64;
629 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
630 die("setrlimit: %m");
633 if (ptrace(PTRACE_TRACEME) < 0)
634 die("ptrace(PTRACE_TRACEME): %m");
635 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
636 signal(SIGCHLD, SIG_IGN);
639 execve(args[0], args, (pass_environ ? environ : env));
640 die("execve(\"%s\"): %m", args[0]);
646 fprintf(stderr, "Invalid arguments!\n");
648 Usage: box [<options>] -- <command> <arguments>\n\
651 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
652 -c <dir>\tChange directory to <dir> first\n\
653 -e\t\tPass full environment of parent process\n\
654 -f\t\tFilter system calls (-ff=very restricted)\n\
655 -i <file>\tRedirect stdin from <file>\n\
656 -m <size>\tLimit address space to <size> KB\n\
657 -o <file>\tRedirect stdout to <file>\n\
658 -s <sys>\tPermit the specified syscall (be careful)\n\
659 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
660 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
661 -T\t\tAllow syscalls for measuring run time\n\
663 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
669 main(int argc, char **argv)
674 while ((c = getopt(argc, argv, "a:c:efi:m:o:s:t:Tvw:")) >= 0)
678 file_access = atol(optarg);
690 redir_stdin = optarg;
693 memory_limit = atol(optarg);
696 redir_stdout = optarg;
699 if (!set_action(optarg))
703 timeout = 1000*atof(optarg);
706 syscall_action[__NR_times] = SC_YES;
712 wall_timeout = 1000*atof(optarg);
721 if (setreuid(uid, uid) < 0)
727 box_inside(argc-optind, argv+optind);
730 die("Internal error: fell over edge of the world");