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);
99 static struct syscall syscall_tab[] = {
100 #include "syscall-table.h"
102 #define NUM_SYSCALLS (sizeof(syscall_tab)/sizeof(syscall_tab[0]))
105 syscall_name(unsigned int id, char *buf)
107 if (id < NUM_SYSCALLS && syscall_tab[id].name)
108 return syscall_tab[id].name;
111 sprintf(buf, "#%d", id);
117 static struct syscall *
118 syscall_by_name(char *name)
120 for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
121 if (!strcmp(syscall_tab[i].name, name))
122 return &syscall_tab[i];
128 valid_filename(unsigned long addr)
130 char namebuf[4096], *p, *end;
134 die("File access forbidden");
135 if (file_access >= 9)
140 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
141 mem_fd = open(namebuf, O_RDONLY);
143 die("open(%s): %m", namebuf);
150 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
151 int l = namebuf + sizeof(namebuf) - end;
155 die("Access to file with name too long");
156 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
157 die("long_seek(mem): %m");
158 remains = read(mem_fd, end, l);
160 die("read(mem): %m");
162 die("Access to file with name out of memory");
169 msg("[%s] ", namebuf);
170 if (file_access >= 3)
172 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
174 if (file_access >= 2)
176 if ((!strncmp(namebuf, "/etc/", 5) ||
177 !strncmp(namebuf, "/lib/", 5) ||
178 !strncmp(namebuf, "/usr/lib/", 9) ||
179 !strncmp(namebuf, "/opt/lib/", 9))
180 && !strstr(namebuf, ".."))
182 if (!strcmp(namebuf, "/dev/null") ||
183 !strcmp(namebuf, "/dev/zero") ||
184 !strcmp(namebuf, "/proc/meminfo") ||
185 !strcmp(namebuf, "/proc/self/stat") ||
186 !strcmp(namebuf, "/proc/self/exe") || /* Needed by FPC 2.0.x runtime */
187 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
190 die("Forbidden access to file `%s'", namebuf);
194 valid_syscall(struct user *u)
196 switch (u->regs.orig_eax)
207 case __NR_truncate64:
211 valid_filename(u->regs.ebx);
229 case __NR_personality:
241 case __NR_ftruncate64:
250 case __NR_set_thread_area:
251 case __NR_get_thread_area:
252 case __NR_exit_group:
262 case __NR_sigsuspend:
263 case __NR_sigpending:
266 case __NR_gettimeofday:
273 case __NR_sigprocmask:
275 case __NR_getdents64:
276 case __NR__newselect:
282 case __NR_rt_sigreturn:
283 case __NR_rt_sigaction:
284 case __NR_rt_sigprocmask:
285 case __NR_rt_sigpending:
286 case __NR_rt_sigtimedwait:
287 case __NR_rt_sigqueueinfo:
288 case __NR_rt_sigsuspend:
291 return (filter_syscalls == 1);
295 if (u->regs.ebx == box_pid)
296 die("Committed suicide by signal %d", (int)u->regs.ecx);
299 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
300 die("Committed suicide by signal %d", (int)u->regs.edx);
308 signal_alarm(int unused UNUSED)
310 /* Time limit checks are synchronous, so we only schedule them there. */
316 signal_int(int unused UNUSED)
318 /* Interrupts are fatal, so no synchronization requirements. */
327 struct timeval now, wall;
329 gettimeofday(&now, NULL);
330 timersub(&now, &start_time, &wall);
331 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
332 if (wall_ms > wall_timeout)
333 die("Time limit exceeded (wall clock)");
335 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
340 int c, utime, stime, ms;
341 static int proc_status_fd;
344 sprintf(buf, "/proc/%d/stat", (int) box_pid);
345 proc_status_fd = open(buf, O_RDONLY);
346 if (proc_status_fd < 0)
347 die("open(%s): %m", buf);
349 lseek(proc_status_fd, 0, SEEK_SET);
350 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
351 die("read on /proc/$pid/stat: %m");
352 if (c >= (int) sizeof(buf) - 1)
353 die("/proc/$pid/stat too long");
356 while (*x && *x != ' ')
361 die("proc syntax error 1");
362 while (*x && (*x != ')' || x[1] != ' '))
364 while (*x == ')' || *x == ' ')
366 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
367 die("proc syntax error 2");
368 ms = (utime + stime) * 1000 / ticks_per_sec;
370 fprintf(stderr, "[time check: %d msec]\n", ms);
372 die("Time limit exceeded");
379 int syscall_count = 0;
383 bzero(&sa, sizeof(sa));
384 sa.sa_handler = signal_int;
385 sigaction(SIGINT, &sa, NULL);
386 gettimeofday(&start_time, NULL);
387 ticks_per_sec = sysconf(_SC_CLK_TCK);
388 if (ticks_per_sec <= 0)
389 die("Invalid ticks_per_sec!");
390 if (timeout || wall_timeout)
392 sa.sa_handler = signal_alarm;
393 sigaction(SIGALRM, &sa, NULL);
406 p = wait4(box_pid, &stat, WUNTRACED, &rus);
414 die("wait4: unknown pid %d exited!", p);
417 struct timeval total, now, wall;
418 int total_ms, wall_ms;
420 if (WEXITSTATUS(stat))
421 die("Exited with error status %d", WEXITSTATUS(stat));
422 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
423 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
424 gettimeofday(&now, NULL);
425 timersub(&now, &start_time, &wall);
426 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
427 if (timeout && total_ms > timeout)
428 die("Time limit exceeded");
429 if (wall_timeout && wall_ms > wall_timeout)
430 die("Time limit exceeded (wall clock)");
431 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
432 (int) total.tv_sec, (int) total.tv_usec/1000,
433 (int) wall.tv_sec, (int) wall.tv_usec/1000,
437 if (WIFSIGNALED(stat))
440 die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
442 if (WIFSTOPPED(stat))
444 int sig = WSTOPSIG(stat);
448 static int stop_count = -1;
449 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
450 die("ptrace(PTRACE_GETREGS): %m");
452 if (!stop_count) /* Traceme request */
453 msg(">> Traceme request caught\n");
454 else if (stop_count & 1) /* Syscall entry */
457 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
461 if (u.regs.orig_eax == __NR_execve)
464 else if (valid_syscall(&u))
469 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
470 * so we have to change it to something harmless (e.g., an undefined
471 * syscall) and make the program continue.
473 unsigned int sys = u.regs.orig_eax;
474 u.regs.orig_eax = 0xffffffff;
475 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
476 die("ptrace(PTRACE_SETREGS): %m");
477 die("Forbidden syscall %s", syscall_name(sys, namebuf));
480 else /* Syscall return */
481 msg("= %ld\n", u.regs.eax);
482 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
484 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
486 msg(">> Signal %d\n", sig);
487 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
490 die("Received signal %d", sig);
493 die("wait4: unknown status %x, giving up!", stat);
498 box_inside(int argc, char **argv)
502 char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
504 memcpy(args, argv, argc * sizeof(char *));
506 if (set_cwd && chdir(set_cwd))
511 if (open(redir_stdin, O_RDONLY) != 0)
512 die("open(\"%s\"): %m", redir_stdin);
517 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
518 die("open(\"%s\"): %m", redir_stdout);
524 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
525 if (setrlimit(RLIMIT_AS, &rl) < 0)
526 die("setrlimit: %m");
528 rl.rlim_cur = rl.rlim_max = 64;
529 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
530 die("setrlimit: %m");
533 if (ptrace(PTRACE_TRACEME) < 0)
534 die("ptrace(PTRACE_TRACEME): %m");
535 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
536 signal(SIGCHLD, SIG_IGN);
539 execve(args[0], args, (pass_environ ? environ : env));
540 die("execve(\"%s\"): %m", args[0]);
546 fprintf(stderr, "Invalid arguments!\n");
548 Usage: box [<options>] -- <command> <arguments>\n\
551 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
552 -c <dir>\tChange directory to <dir> first\n\
553 -e\t\tPass full environment of parent process\n\
554 -f\t\tFilter system calls (-ff=very restricted)\n\
555 -i <file>\tRedirect stdin from <file>\n\
556 -m <size>\tLimit address space to <size> KB\n\
557 -o <file>\tRedirect stdout to <file>\n\
558 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
559 -T\t\tAllow syscalls for measuring run time\n\
561 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
567 main(int argc, char **argv)
572 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw:")) >= 0)
576 file_access = atol(optarg);
588 redir_stdin = optarg;
591 memory_limit = atol(optarg);
594 redir_stdout = optarg;
597 timeout = 1000*atof(optarg);
606 wall_timeout = 1000*atof(optarg);
615 if (setreuid(uid, uid) < 0)
621 box_inside(argc-optind, argv+optind);
624 die("Internal error: fell over edge of the world");