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_names[] = {
95 #include "syscall-table.h"
97 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
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_names[id])
214 return syscall_names[id];
217 sprintf(buf, "#%d", id);
223 syscall_by_name(char *name)
225 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
226 if (syscall_names[i] && !strcmp(syscall_names[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 >= 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 { "/usr/share/locale/", SC_YES },
281 { "/dev/null", SC_YES },
282 { "/dev/zero", SC_YES },
283 { "/proc/meminfo", SC_YES },
284 { "/proc/self/stat", SC_YES },
285 { "/proc/self/exe", SC_YES }, // Needed by FPC 2.0.x runtime
289 match_path_rule(struct path_rule *r, char *path)
293 if (*rr++ != *path++)
295 if (rr[-1] == '/' && !path[-1])
299 if (rr > r->path && rr[-1] != '/' && *path)
305 valid_filename(unsigned long addr)
307 char namebuf[4096], *p, *end;
311 die("File access forbidden");
312 if (file_access >= 9)
317 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
318 mem_fd = open(namebuf, O_RDONLY);
320 die("open(%s): %m", namebuf);
327 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
328 int l = namebuf + sizeof(namebuf) - end;
332 die("Access to file with name too long");
333 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
334 die("long_seek(mem): %m");
335 remains = read(mem_fd, end, l);
337 die("read(mem): %m");
339 die("Access to file with name out of memory");
346 msg("[%s] ", namebuf);
347 if (file_access >= 3)
350 // Everything in current directory is permitted
351 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
354 // ".." anywhere in the path is forbidden
355 enum action act = SC_DEFAULT;
356 if (strstr(namebuf, ".."))
359 // Scan built-in rules
360 if (file_access >= 2)
361 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
362 act = match_path_rule(&default_path_rules[i], namebuf);
365 die("Forbidden access to file `%s'", namebuf);
369 valid_syscall(struct user *u)
371 unsigned int sys = u->regs.orig_eax;
372 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
374 if (act & SC_LIBERAL)
376 if (filter_syscalls == 1)
388 valid_filename(u->regs.ebx);
396 if (u->regs.ebx == box_pid)
397 die("Committed suicide by signal %d", (int)u->regs.ecx);
400 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
401 die("Committed suicide by signal %d", (int)u->regs.edx);
409 signal_alarm(int unused UNUSED)
411 /* Time limit checks are synchronous, so we only schedule them there. */
417 signal_int(int unused UNUSED)
419 /* Interrupts are fatal, so no synchronization requirements. */
428 struct timeval now, wall;
430 gettimeofday(&now, NULL);
431 timersub(&now, &start_time, &wall);
432 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
433 if (wall_ms > wall_timeout)
434 die("Time limit exceeded (wall clock)");
436 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
441 int c, utime, stime, ms;
442 static int proc_status_fd;
445 sprintf(buf, "/proc/%d/stat", (int) box_pid);
446 proc_status_fd = open(buf, O_RDONLY);
447 if (proc_status_fd < 0)
448 die("open(%s): %m", buf);
450 lseek(proc_status_fd, 0, SEEK_SET);
451 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
452 die("read on /proc/$pid/stat: %m");
453 if (c >= (int) sizeof(buf) - 1)
454 die("/proc/$pid/stat too long");
457 while (*x && *x != ' ')
462 die("proc syntax error 1");
463 while (*x && (*x != ')' || x[1] != ' '))
465 while (*x == ')' || *x == ' ')
467 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
468 die("proc syntax error 2");
469 ms = (utime + stime) * 1000 / ticks_per_sec;
471 fprintf(stderr, "[time check: %d msec]\n", ms);
473 die("Time limit exceeded");
480 int syscall_count = 0;
484 bzero(&sa, sizeof(sa));
485 sa.sa_handler = signal_int;
486 sigaction(SIGINT, &sa, NULL);
487 gettimeofday(&start_time, NULL);
488 ticks_per_sec = sysconf(_SC_CLK_TCK);
489 if (ticks_per_sec <= 0)
490 die("Invalid ticks_per_sec!");
491 if (timeout || wall_timeout)
493 sa.sa_handler = signal_alarm;
494 sigaction(SIGALRM, &sa, NULL);
507 p = wait4(box_pid, &stat, WUNTRACED, &rus);
515 die("wait4: unknown pid %d exited!", p);
518 struct timeval total, now, wall;
519 int total_ms, wall_ms;
521 if (WEXITSTATUS(stat))
522 die("Exited with error status %d", WEXITSTATUS(stat));
523 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
524 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
525 gettimeofday(&now, NULL);
526 timersub(&now, &start_time, &wall);
527 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
528 if (timeout && total_ms > timeout)
529 die("Time limit exceeded");
530 if (wall_timeout && wall_ms > wall_timeout)
531 die("Time limit exceeded (wall clock)");
532 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
533 (int) total.tv_sec, (int) total.tv_usec/1000,
534 (int) wall.tv_sec, (int) wall.tv_usec/1000,
538 if (WIFSIGNALED(stat))
541 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
543 if (WIFSTOPPED(stat))
545 int sig = WSTOPSIG(stat);
549 static int stop_count = -1;
550 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
551 die("ptrace(PTRACE_GETREGS): %m");
553 if (!stop_count) /* Traceme request */
554 msg(">> Traceme request caught\n");
555 else if (stop_count & 1) /* Syscall entry */
558 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
562 if (u.regs.orig_eax == __NR_execve)
565 else if (valid_syscall(&u))
570 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
571 * so we have to change it to something harmless (e.g., an undefined
572 * syscall) and make the program continue.
574 unsigned int sys = u.regs.orig_eax;
575 u.regs.orig_eax = 0xffffffff;
576 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
577 die("ptrace(PTRACE_SETREGS): %m");
578 die("Forbidden syscall %s", syscall_name(sys, namebuf));
581 else /* Syscall return */
582 msg("= %ld\n", u.regs.eax);
583 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
585 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
587 msg(">> Signal %d\n", sig);
588 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
591 die("Received signal %d", sig);
594 die("wait4: unknown status %x, giving up!", stat);
599 box_inside(int argc, char **argv)
603 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
605 memcpy(args, argv, argc * sizeof(char *));
607 if (set_cwd && chdir(set_cwd))
612 if (open(redir_stdin, O_RDONLY) != 0)
613 die("open(\"%s\"): %m", redir_stdin);
618 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
619 die("open(\"%s\"): %m", redir_stdout);
625 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
626 if (setrlimit(RLIMIT_AS, &rl) < 0)
627 die("setrlimit: %m");
629 rl.rlim_cur = rl.rlim_max = 64;
630 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
631 die("setrlimit: %m");
634 if (ptrace(PTRACE_TRACEME) < 0)
635 die("ptrace(PTRACE_TRACEME): %m");
636 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
637 signal(SIGCHLD, SIG_IGN);
640 execve(args[0], args, (pass_environ ? environ : env));
641 die("execve(\"%s\"): %m", args[0]);
647 fprintf(stderr, "Invalid arguments!\n");
649 Usage: box [<options>] -- <command> <arguments>\n\
652 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
653 -c <dir>\tChange directory to <dir> first\n\
654 -e\t\tPass full environment of parent process\n\
655 -f\t\tFilter system calls (-ff=very restricted)\n\
656 -i <file>\tRedirect stdin from <file>\n\
657 -m <size>\tLimit address space to <size> KB\n\
658 -o <file>\tRedirect stdout to <file>\n\
659 -s <sys>\tPermit the specified syscall (be careful)\n\
660 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
661 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
662 -T\t\tAllow syscalls for measuring run time\n\
664 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
670 main(int argc, char **argv)
675 while ((c = getopt(argc, argv, "a:c:efi:m:o:s:t:Tvw:")) >= 0)
679 file_access = atol(optarg);
691 redir_stdin = optarg;
694 memory_limit = atol(optarg);
697 redir_stdout = optarg;
700 if (!set_action(optarg))
704 timeout = 1000*atof(optarg);
707 syscall_action[__NR_times] = SC_YES;
713 wall_timeout = 1000*atof(optarg);
722 if (setreuid(uid, uid) < 0)
728 box_inside(argc-optind, argv+optind);
731 die("Internal error: fell over edge of the world");