2 * A Simple Testing Sandbox
4 * (c) 2001--2007 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 int allow_times;
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);
95 valid_filename(unsigned long addr)
97 char namebuf[4096], *p, *end;
101 die("File access forbidden");
102 if (file_access >= 9)
107 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
108 mem_fd = open(namebuf, O_RDONLY);
110 die("open(%s): %m", namebuf);
117 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
118 int l = namebuf + sizeof(namebuf) - end;
122 die("Access to file with name too long");
123 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
124 die("long_seek(mem): %m");
125 remains = read(mem_fd, end, l);
127 die("read(mem): %m");
129 die("Access to file with name out of memory");
136 msg("[%s] ", namebuf);
137 if (file_access >= 3)
139 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
141 if (file_access >= 2)
143 if ((!strncmp(namebuf, "/etc/", 5) ||
144 !strncmp(namebuf, "/lib/", 5) ||
145 !strncmp(namebuf, "/usr/lib/", 9) ||
146 !strncmp(namebuf, "/opt/lib/", 9))
147 && !strstr(namebuf, ".."))
149 if (!strcmp(namebuf, "/dev/null") ||
150 !strcmp(namebuf, "/dev/zero") ||
151 !strcmp(namebuf, "/proc/meminfo") ||
152 !strcmp(namebuf, "/proc/self/stat") ||
153 !strcmp(namebuf, "/proc/self/exe") || /* Needed by FPC 2.0.x runtime */
154 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
157 die("Forbidden access to file `%s'", namebuf);
161 valid_syscall(struct user *u)
163 switch (u->regs.orig_eax)
174 case __NR_truncate64:
178 valid_filename(u->regs.ebx);
196 case __NR_personality:
208 case __NR_ftruncate64:
217 case __NR_set_thread_area:
218 case __NR_get_thread_area:
219 case __NR_exit_group:
229 case __NR_sigsuspend:
230 case __NR_sigpending:
233 case __NR_gettimeofday:
240 case __NR_sigprocmask:
242 case __NR_getdents64:
243 case __NR__newselect:
249 case __NR_rt_sigreturn:
250 case __NR_rt_sigaction:
251 case __NR_rt_sigprocmask:
252 case __NR_rt_sigpending:
253 case __NR_rt_sigtimedwait:
254 case __NR_rt_sigqueueinfo:
255 case __NR_rt_sigsuspend:
258 return (filter_syscalls == 1);
262 if (u->regs.ebx == box_pid)
263 die("Committed suicide by signal %d", (int)u->regs.ecx);
266 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
267 die("Committed suicide by signal %d", (int)u->regs.edx);
275 signal_alarm(int unused UNUSED)
277 /* Time limit checks are synchronous, so we only schedule them there. */
283 signal_int(int unused UNUSED)
285 /* Interrupts are fatal, so no synchronization requirements. */
294 struct timeval now, wall;
296 gettimeofday(&now, NULL);
297 timersub(&now, &start_time, &wall);
298 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
299 if (wall_ms > wall_timeout)
300 die("Time limit exceeded (wall clock)");
302 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
307 int c, utime, stime, ms;
308 static int proc_status_fd;
311 sprintf(buf, "/proc/%d/stat", (int) box_pid);
312 proc_status_fd = open(buf, O_RDONLY);
313 if (proc_status_fd < 0)
314 die("open(%s): %m", buf);
316 lseek(proc_status_fd, 0, SEEK_SET);
317 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
318 die("read on /proc/$pid/stat: %m");
319 if (c >= (int) sizeof(buf) - 1)
320 die("/proc/$pid/stat too long");
323 while (*x && *x != ' ')
328 die("proc syntax error 1");
329 while (*x && (*x != ')' || x[1] != ' '))
331 while (*x == ')' || *x == ' ')
333 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
334 die("proc syntax error 2");
335 ms = (utime + stime) * 1000 / ticks_per_sec;
337 fprintf(stderr, "[time check: %d msec]\n", ms);
339 die("Time limit exceeded");
346 int syscall_count = 0;
350 bzero(&sa, sizeof(sa));
351 sa.sa_handler = signal_int;
352 sigaction(SIGINT, &sa, NULL);
353 gettimeofday(&start_time, NULL);
354 ticks_per_sec = sysconf(_SC_CLK_TCK);
355 if (ticks_per_sec <= 0)
356 die("Invalid ticks_per_sec!");
357 if (timeout || wall_timeout)
359 sa.sa_handler = signal_alarm;
360 sigaction(SIGALRM, &sa, NULL);
373 p = wait4(box_pid, &stat, WUNTRACED, &rus);
381 die("wait4: unknown pid %d exited!", p);
384 struct timeval total, now, wall;
385 int total_ms, wall_ms;
387 if (WEXITSTATUS(stat))
388 die("Exited with error status %d", WEXITSTATUS(stat));
389 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
390 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
391 gettimeofday(&now, NULL);
392 timersub(&now, &start_time, &wall);
393 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
394 if (timeout && total_ms > timeout)
395 die("Time limit exceeded");
396 if (wall_timeout && wall_ms > wall_timeout)
397 die("Time limit exceeded (wall clock)");
398 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
399 (int) total.tv_sec, (int) total.tv_usec/1000,
400 (int) wall.tv_sec, (int) wall.tv_usec/1000,
404 if (WIFSIGNALED(stat))
407 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
409 if (WIFSTOPPED(stat))
411 int sig = WSTOPSIG(stat);
415 static int stop_count = -1;
416 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
417 die("ptrace(PTRACE_GETREGS): %m");
419 if (!stop_count) /* Traceme request */
420 msg(">> Traceme request caught\n");
421 else if (stop_count & 1) /* Syscall entry */
423 msg(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
427 if (u.regs.orig_eax == __NR_execve)
430 else if (valid_syscall(&u))
435 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
436 * so we have to change it to something harmless (e.g., an undefined
437 * syscall) and make the program continue.
439 unsigned int sys = u.regs.orig_eax;
440 u.regs.orig_eax = 0xffffffff;
441 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
442 die("ptrace(PTRACE_SETREGS): %m");
443 die("Forbidden syscall %d", sys);
446 else /* Syscall return */
447 msg("= %ld\n", u.regs.eax);
448 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
450 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
452 msg(">> Signal %d\n", sig);
453 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
456 die("Received signal %d", sig);
459 die("wait4: unknown status %x, giving up!", stat);
464 box_inside(int argc, char **argv)
468 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
470 memcpy(args, argv, argc * sizeof(char *));
472 if (set_cwd && chdir(set_cwd))
477 if (open(redir_stdin, O_RDONLY) != 0)
478 die("open(\"%s\"): %m", redir_stdin);
483 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
484 die("open(\"%s\"): %m", redir_stdout);
490 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
491 if (setrlimit(RLIMIT_AS, &rl) < 0)
492 die("setrlimit: %m");
494 rl.rlim_cur = rl.rlim_max = 64;
495 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
496 die("setrlimit: %m");
499 if (ptrace(PTRACE_TRACEME) < 0)
500 die("ptrace(PTRACE_TRACEME): %m");
501 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
502 signal(SIGCHLD, SIG_IGN);
505 execve(args[0], args, (pass_environ ? environ : env));
506 die("execve(\"%s\"): %m", args[0]);
512 fprintf(stderr, "Invalid arguments!\n");
514 Usage: box [<options>] -- <command> <arguments>\n\
517 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
518 -c <dir>\tChange directory to <dir> first\n\
519 -e\t\tPass full environment of parent process\n\
520 -f\t\tFilter system calls (-ff=very restricted)\n\
521 -i <file>\tRedirect stdin from <file>\n\
522 -m <size>\tLimit address space to <size> KB\n\
523 -o <file>\tRedirect stdout to <file>\n\
524 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
525 -T\t\tAllow syscalls for measuring run time\n\
527 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
533 main(int argc, char **argv)
538 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw:")) >= 0)
542 file_access = atol(optarg);
554 redir_stdin = optarg;
557 memory_limit = atol(optarg);
560 redir_stdout = optarg;
563 timeout = 1000*atof(optarg);
572 wall_timeout = 1000*atof(optarg);
581 if (setreuid(uid, uid) < 0)
587 box_inside(argc-optind, argv+optind);
590 die("Internal error: fell over edge of the world");