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);
97 void *p = malloc(size);
103 static const char * const syscall_names[] = {
104 #include "syscall-table.h"
106 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
107 #define NUM_ACTIONS (NUM_SYSCALLS+64)
110 SC_DEFAULT, // Use the default action
111 SC_NO, // Always forbid
112 SC_YES, // Always permit
113 SC_FILENAME, // Permit if arg1 is a known filename
114 SC_LIBERAL = 128, // Valid only in liberal mode
117 static unsigned char syscall_action[NUM_ACTIONS] = {
118 #define S(x) [__NR_##x]
120 // Syscalls permitted for specific file names
121 S(open) = SC_FILENAME,
122 S(creat) = SC_FILENAME,
123 S(unlink) = SC_FILENAME,
124 S(oldstat) = SC_FILENAME,
125 S(access) = SC_FILENAME,
126 S(oldlstat) = SC_FILENAME,
127 S(truncate) = SC_FILENAME,
128 S(stat) = SC_FILENAME,
129 S(lstat) = SC_FILENAME,
130 S(truncate64) = SC_FILENAME,
131 S(stat64) = SC_FILENAME,
132 S(lstat64) = SC_FILENAME,
133 S(readlink) = SC_FILENAME,
135 // Syscalls permitted always
143 S(oldfstat) = SC_YES,
150 S(ftruncate) = SC_YES,
152 S(personality) = SC_YES,
156 S(getresuid) = SC_YES,
159 S(pwrite64) = SC_YES,
164 S(ftruncate64) = SC_YES,
173 S(set_thread_area) = SC_YES,
174 S(get_thread_area) = SC_YES,
175 S(exit_group) = SC_YES,
177 // Syscalls permitted only in liberal mode
178 S(time) = SC_YES | SC_LIBERAL,
179 S(alarm) = SC_YES | SC_LIBERAL,
180 S(pause) = SC_YES | SC_LIBERAL,
181 S(signal) = SC_YES | SC_LIBERAL,
182 S(fchmod) = SC_YES | SC_LIBERAL,
183 S(sigaction) = SC_YES | SC_LIBERAL,
184 S(sgetmask) = SC_YES | SC_LIBERAL,
185 S(ssetmask) = SC_YES | SC_LIBERAL,
186 S(sigsuspend) = SC_YES | SC_LIBERAL,
187 S(sigpending) = SC_YES | SC_LIBERAL,
188 S(getrlimit) = SC_YES | SC_LIBERAL,
189 S(getrusage) = SC_YES | SC_LIBERAL,
190 S(ugetrlimit) = SC_YES | SC_LIBERAL,
191 S(gettimeofday) = SC_YES | SC_LIBERAL,
192 S(select) = SC_YES | SC_LIBERAL,
193 S(readdir) = SC_YES | SC_LIBERAL,
194 S(setitimer) = SC_YES | SC_LIBERAL,
195 S(getitimer) = SC_YES | SC_LIBERAL,
196 S(sigreturn) = SC_YES | SC_LIBERAL,
197 S(mprotect) = SC_YES | SC_LIBERAL,
198 S(sigprocmask) = SC_YES | SC_LIBERAL,
199 S(getdents) = SC_YES | SC_LIBERAL,
200 S(getdents64) = SC_YES | SC_LIBERAL,
201 S(_newselect) = SC_YES | SC_LIBERAL,
202 S(fdatasync) = SC_YES | SC_LIBERAL,
203 S(mremap) = SC_YES | SC_LIBERAL,
204 S(poll) = SC_YES | SC_LIBERAL,
205 S(getcwd) = SC_YES | SC_LIBERAL,
206 S(nanosleep) = SC_YES | SC_LIBERAL,
207 S(rt_sigreturn) = SC_YES | SC_LIBERAL,
208 S(rt_sigaction) = SC_YES | SC_LIBERAL,
209 S(rt_sigprocmask) = SC_YES | SC_LIBERAL,
210 S(rt_sigpending) = SC_YES | SC_LIBERAL,
211 S(rt_sigtimedwait) = SC_YES | SC_LIBERAL,
212 S(rt_sigqueueinfo) = SC_YES | SC_LIBERAL,
213 S(rt_sigsuspend) = SC_YES | SC_LIBERAL,
214 S(mmap2) = SC_YES | SC_LIBERAL,
215 S(_sysctl) = SC_YES | SC_LIBERAL,
220 syscall_name(unsigned int id, char *buf)
222 if (id < NUM_SYSCALLS && syscall_names[id])
223 return syscall_names[id];
226 sprintf(buf, "#%d", id);
232 syscall_by_name(char *name)
234 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
235 if (syscall_names[i] && !strcmp(syscall_names[i], name))
242 unsigned long l = strtoul(name, &ep, 0);
245 if (l >= NUM_ACTIONS)
251 set_syscall_action(char *a)
253 char *sep = strchr(a, '=');
254 enum action act = SC_YES;
258 if (!strcmp(sep, "yes"))
260 else if (!strcmp(sep, "no"))
262 else if (!strcmp(sep, "file"))
268 int sys = syscall_by_name(a);
270 die("Unknown syscall `%s'", a);
271 if (sys >= NUM_ACTIONS)
272 die("Syscall `%s' out of range", a);
273 syscall_action[sys] = act;
280 struct path_rule *next;
283 static struct path_rule default_path_rules[] = {
286 { "/usr/lib/", SC_YES },
287 { "/opt/lib/", SC_YES },
288 { "/usr/share/zoneinfo/", SC_YES },
289 { "/usr/share/locale/", SC_YES },
290 { "/dev/null", SC_YES },
291 { "/dev/zero", SC_YES },
292 { "/proc/meminfo", SC_YES },
293 { "/proc/self/stat", SC_YES },
294 { "/proc/self/exe", SC_YES }, // Needed by FPC 2.0.x runtime
297 static struct path_rule *user_path_rules;
298 static struct path_rule **last_path_rule = &user_path_rules;
301 set_path_action(char *a)
303 char *sep = strchr(a, '=');
304 enum action act = SC_YES;
308 if (!strcmp(sep, "yes"))
310 else if (!strcmp(sep, "no"))
316 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a));
317 r->path = (char *)(r+1);
322 last_path_rule = &r->next;
327 match_path_rule(struct path_rule *r, char *path)
331 if (*rr++ != *path++)
333 if (rr[-1] == '/' && !path[-1])
337 if (rr > r->path && rr[-1] != '/' && *path)
343 valid_filename(unsigned long addr)
345 char namebuf[4096], *p, *end;
349 die("File access forbidden");
350 if (file_access >= 9)
355 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
356 mem_fd = open(namebuf, O_RDONLY);
358 die("open(%s): %m", namebuf);
365 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
366 int l = namebuf + sizeof(namebuf) - end;
370 die("Access to file with name too long");
371 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
372 die("long_seek(mem): %m");
373 remains = read(mem_fd, end, l);
375 die("read(mem): %m");
377 die("Access to file with name out of memory");
384 msg("[%s] ", namebuf);
385 if (file_access >= 3)
388 // Everything in current directory is permitted
389 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
392 // ".." anywhere in the path is forbidden
393 enum action act = SC_DEFAULT;
394 if (strstr(namebuf, ".."))
398 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
399 act = match_path_rule(r, namebuf);
401 // Scan built-in rules
402 if (file_access >= 2)
403 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
404 act = match_path_rule(&default_path_rules[i], namebuf);
407 die("Forbidden access to file `%s'", namebuf);
411 valid_syscall(struct user *u)
413 unsigned int sys = u->regs.orig_eax;
414 enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
416 if (act & SC_LIBERAL)
418 if (filter_syscalls == 1)
430 valid_filename(u->regs.ebx);
438 if (u->regs.ebx == box_pid)
439 die("Committed suicide by signal %d", (int)u->regs.ecx);
442 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
443 die("Committed suicide by signal %d", (int)u->regs.edx);
451 signal_alarm(int unused UNUSED)
453 /* Time limit checks are synchronous, so we only schedule them there. */
459 signal_int(int unused UNUSED)
461 /* Interrupts are fatal, so no synchronization requirements. */
470 struct timeval now, wall;
472 gettimeofday(&now, NULL);
473 timersub(&now, &start_time, &wall);
474 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
475 if (wall_ms > wall_timeout)
476 die("Time limit exceeded (wall clock)");
478 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
483 int c, utime, stime, ms;
484 static int proc_status_fd;
487 sprintf(buf, "/proc/%d/stat", (int) box_pid);
488 proc_status_fd = open(buf, O_RDONLY);
489 if (proc_status_fd < 0)
490 die("open(%s): %m", buf);
492 lseek(proc_status_fd, 0, SEEK_SET);
493 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
494 die("read on /proc/$pid/stat: %m");
495 if (c >= (int) sizeof(buf) - 1)
496 die("/proc/$pid/stat too long");
499 while (*x && *x != ' ')
504 die("proc syntax error 1");
505 while (*x && (*x != ')' || x[1] != ' '))
507 while (*x == ')' || *x == ' ')
509 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
510 die("proc syntax error 2");
511 ms = (utime + stime) * 1000 / ticks_per_sec;
513 fprintf(stderr, "[time check: %d msec]\n", ms);
515 die("Time limit exceeded");
522 int syscall_count = 0;
526 bzero(&sa, sizeof(sa));
527 sa.sa_handler = signal_int;
528 sigaction(SIGINT, &sa, NULL);
529 gettimeofday(&start_time, NULL);
530 ticks_per_sec = sysconf(_SC_CLK_TCK);
531 if (ticks_per_sec <= 0)
532 die("Invalid ticks_per_sec!");
533 if (timeout || wall_timeout)
535 sa.sa_handler = signal_alarm;
536 sigaction(SIGALRM, &sa, NULL);
549 p = wait4(box_pid, &stat, WUNTRACED, &rus);
557 die("wait4: unknown pid %d exited!", p);
560 struct timeval total, now, wall;
561 int total_ms, wall_ms;
563 if (WEXITSTATUS(stat))
564 die("Exited with error status %d", WEXITSTATUS(stat));
565 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
566 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
567 gettimeofday(&now, NULL);
568 timersub(&now, &start_time, &wall);
569 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
570 if (timeout && total_ms > timeout)
571 die("Time limit exceeded");
572 if (wall_timeout && wall_ms > wall_timeout)
573 die("Time limit exceeded (wall clock)");
574 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
575 (int) total.tv_sec, (int) total.tv_usec/1000,
576 (int) wall.tv_sec, (int) wall.tv_usec/1000,
580 if (WIFSIGNALED(stat))
583 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
585 if (WIFSTOPPED(stat))
587 int sig = WSTOPSIG(stat);
591 static int stop_count = -1;
592 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
593 die("ptrace(PTRACE_GETREGS): %m");
595 if (!stop_count) /* Traceme request */
596 msg(">> Traceme request caught\n");
597 else if (stop_count & 1) /* Syscall entry */
600 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
604 if (u.regs.orig_eax == __NR_execve)
607 else if (valid_syscall(&u))
612 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
613 * so we have to change it to something harmless (e.g., an undefined
614 * syscall) and make the program continue.
616 unsigned int sys = u.regs.orig_eax;
617 u.regs.orig_eax = 0xffffffff;
618 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
619 die("ptrace(PTRACE_SETREGS): %m");
620 die("Forbidden syscall %s", syscall_name(sys, namebuf));
623 else /* Syscall return */
624 msg("= %ld\n", u.regs.eax);
625 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
627 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
629 msg(">> Signal %d\n", sig);
630 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
633 die("Received signal %d", sig);
636 die("wait4: unknown status %x, giving up!", stat);
641 box_inside(int argc, char **argv)
645 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
647 memcpy(args, argv, argc * sizeof(char *));
649 if (set_cwd && chdir(set_cwd))
654 if (open(redir_stdin, O_RDONLY) != 0)
655 die("open(\"%s\"): %m", redir_stdin);
660 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
661 die("open(\"%s\"): %m", redir_stdout);
667 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
668 if (setrlimit(RLIMIT_AS, &rl) < 0)
669 die("setrlimit: %m");
671 rl.rlim_cur = rl.rlim_max = 64;
672 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
673 die("setrlimit: %m");
676 if (ptrace(PTRACE_TRACEME) < 0)
677 die("ptrace(PTRACE_TRACEME): %m");
678 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
679 signal(SIGCHLD, SIG_IGN);
682 execve(args[0], args, (pass_environ ? environ : env));
683 die("execve(\"%s\"): %m", args[0]);
689 fprintf(stderr, "Invalid arguments!\n");
691 Usage: box [<options>] -- <command> <arguments>\n\
694 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
695 -c <dir>\tChange directory to <dir> first\n\
696 -e\t\tPass full environment of parent process\n\
697 -f\t\tFilter system calls (-ff=very restricted)\n\
698 -i <file>\tRedirect stdin from <file>\n\
699 -m <size>\tLimit address space to <size> KB\n\
700 -o <file>\tRedirect stdout to <file>\n\
701 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
702 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
703 -s <sys>\tPermit the specified syscall (be careful)\n\
704 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
705 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
706 -T\t\tAllow syscalls for measuring run time\n\
708 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
714 main(int argc, char **argv)
719 while ((c = getopt(argc, argv, "a:c:efi:m:o:p:s:t:Tvw:")) >= 0)
723 file_access = atol(optarg);
735 redir_stdin = optarg;
738 memory_limit = atol(optarg);
741 redir_stdout = optarg;
744 if (!set_path_action(optarg))
748 if (!set_syscall_action(optarg))
752 timeout = 1000*atof(optarg);
755 syscall_action[__NR_times] = SC_YES;
761 wall_timeout = 1000*atof(optarg);
770 if (setreuid(uid, uid) < 0)
776 box_inside(argc-optind, argv+optind);
779 die("Internal error: fell over edge of the world");