2 * A Simple Testing Sandbox
4 * (c) 2001 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 */
33 static int pass_environ;
34 static int use_wall_clock;
35 static int file_access;
37 static int memory_limit;
38 static int allow_times;
39 static char *redir_stdin, *redir_stdout;
42 static int is_ptraced;
43 static volatile int timer_tick;
44 static time_t start_time;
45 static int ticks_per_sec;
47 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
48 /* glibc 2.1 or newer -> has lseek64 */
49 #define long_seek(f,o,w) lseek64(f,o,w)
51 /* Touching clandestine places in glibc */
52 extern loff_t llseek(int fd, loff_t pos, int whence);
53 #define long_seek(f,o,w) llseek(f,o,w)
62 ptrace(PTRACE_KILL, box_pid);
63 kill(-box_pid, SIGKILL);
64 kill(box_pid, SIGKILL);
69 static void NONRET __attribute__((format(printf,1,2)))
74 vfprintf(stderr, msg, args);
79 static void __attribute__((format(printf,1,2)))
86 vfprintf(stderr, msg, args);
93 valid_filename(unsigned long addr)
95 char namebuf[4096], *p, *end;
99 die("File access forbidden.");
100 if (file_access >= 9)
105 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
106 mem_fd = open(namebuf, O_RDONLY);
108 die("open(%s): %m", namebuf);
115 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
116 int l = namebuf + sizeof(namebuf) - end;
120 die("Access to file with name too long.");
121 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
122 die("long_seek(mem): %m");
123 remains = read(mem_fd, end, l);
125 die("read(mem): %m");
127 die("Access to file with name out of memory.");
134 log("[%s] ", namebuf);
135 if (file_access >= 3)
137 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
139 if (file_access >= 2)
141 if ((!strncmp(namebuf, "/etc/", 5) ||
142 !strncmp(namebuf, "/lib/", 5) ||
143 !strncmp(namebuf, "/usr/lib/", 9))
144 && !strstr(namebuf, ".."))
146 if (!strcmp(namebuf, "/dev/null") ||
147 !strcmp(namebuf, "/dev/zero") ||
148 !strcmp(namebuf, "/proc/meminfo") ||
149 !strcmp(namebuf, "/proc/self/stat") ||
150 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
153 die("Forbidden access to file `%s'.", namebuf);
157 valid_syscall(struct user *u)
159 switch (u->regs.orig_eax)
163 static int exec_counter;
164 return !exec_counter++;
178 valid_filename(u->regs.ebx);
196 case SYS_personality:
203 case SYS_ftruncate64:
225 case SYS_gettimeofday:
232 case SYS_sigprocmask:
241 case SYS_rt_sigreturn:
242 case SYS_rt_sigaction:
243 case SYS_rt_sigprocmask:
244 case SYS_rt_sigpending:
245 case SYS_rt_sigtimedwait:
246 case SYS_rt_sigqueueinfo:
247 case SYS_rt_sigsuspend:
250 return (filter_syscalls == 1);
259 signal_alarm(int unused UNUSED)
261 /* Time limit checks are synchronous, so we only schedule them there. */
267 signal_int(int unused UNUSED)
269 /* Interrupts are fatal, so no synchronization requirements. */
279 sec = time(NULL) - start_time;
284 static int proc_status_fd;
287 sprintf(buf, "/proc/%d/stat", (int) box_pid);
288 proc_status_fd = open(buf, O_RDONLY);
289 if (proc_status_fd < 0)
290 die("open(%s): %m", buf);
292 lseek(proc_status_fd, 0, SEEK_SET);
293 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
294 die("read on /proc/$pid/stat: %m");
295 if (c >= (int) sizeof(buf) - 1)
296 die("/proc/$pid/stat too long");
299 while (*x && *x != ' ')
304 die("proc syntax error 1");
305 while (*x && (*x != ')' || x[1] != ' '))
307 while (*x == ')' || *x == ' ')
309 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
310 die("proc syntax error 2");
311 sec = (utime + stime)/ticks_per_sec;
314 fprintf(stderr, "[timecheck: %d seconds]\n", sec);
316 die("Time limit exceeded.");
322 int syscall_count = 0;
326 bzero(&sa, sizeof(sa));
327 sa.sa_handler = signal_int;
328 sigaction(SIGINT, &sa, NULL);
329 start_time = time(NULL);
330 ticks_per_sec = sysconf(_SC_CLK_TCK);
331 if (ticks_per_sec <= 0)
332 die("Invalid ticks_per_sec!");
335 sa.sa_handler = signal_alarm;
336 sigaction(SIGALRM, &sa, NULL);
349 p = wait4(box_pid, &stat, WUNTRACED, &rus);
357 die("wait4: unknown pid %d exited!", p);
360 struct timeval total;
363 if (WEXITSTATUS(stat))
364 die("Exited with error status %d.", WEXITSTATUS(stat));
365 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
366 wall = time(NULL) - start_time;
367 if ((use_wall_clock ? wall : total.tv_sec) > timeout)
368 die("Time limit exceeded (after exit).");
369 fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
372 if (WIFSIGNALED(stat))
375 die("Caught fatal signal %d.", WTERMSIG(stat));
377 if (WIFSTOPPED(stat))
379 int sig = WSTOPSIG(stat);
383 static int stop_count = -1;
384 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
385 die("ptrace(PTRACE_GETREGS): %m");
387 if (!stop_count) /* Traceme request */
388 log(">> Traceme request caught\n");
389 else if (stop_count & 1) /* Syscall entry */
391 log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
393 if (!valid_syscall(&u))
396 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
397 * so we have to change it to something harmless (e.g., an undefined
398 * syscall) and make the program continue.
400 unsigned int sys = u.regs.orig_eax;
401 u.regs.orig_eax = 0xffffffff;
402 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
403 die("ptrace(PTRACE_SETREGS): %m");
404 die("Forbidden syscall %d.", sys);
407 else /* Syscall return */
408 log("= %ld\n", u.regs.eax);
409 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
411 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
413 log(">> Signal %d\n", sig);
414 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
417 die("Received signal %d.", sig);
420 die("wait4: unknown status %x, giving up!", stat);
425 box_inside(int argc, char **argv)
429 char *env[1] = { NULL };
431 memcpy(args, argv, argc * sizeof(char *));
436 if (open(redir_stdin, O_RDONLY) != 0)
437 die("open(\"%s\"): %m", redir_stdin);
442 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
443 die("open(\"%s\"): %m", redir_stdout);
450 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
451 if (setrlimit(RLIMIT_AS, &rl) < 0)
452 die("setrlimit: %m");
454 rl.rlim_cur = rl.rlim_max = 64;
455 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
456 die("setrlimit: %m");
457 if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
458 die("ptrace(PTRACE_TRACEME): %m");
459 execve(args[0], args, (pass_environ ? environ : env));
460 die("execve(\"%s\"): %m", args[0]);
466 fprintf(stderr, "Invalid arguments!\n");
468 Usage: box [<options>] -- <command> <arguments>\n\
471 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
472 -c <dir>\tChange directory to <dir> first\n\
473 -e\t\tPass full environment of parent process\n\
474 -f\t\tFilter system calls (-ff=very restricted)\n\
475 -i <file>\tRedirect stdin from <file>\n\
476 -m <size>\tLimit address space to <size> KB\n\
477 -o <file>\tRedirect stdout to <file>\n\
478 -t <time>\tStop after <time> seconds\n\
479 -T\t\tAllow syscalls for measuring run time\n\
481 -w\t\tMeasure wall clock time instead of run time\n\
487 main(int argc, char **argv)
493 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw")) >= 0)
497 file_access = atol(optarg);
509 redir_stdin = optarg;
512 memory_limit = atol(optarg);
515 redir_stdout = optarg;
518 timeout = atol(optarg);
536 if (setreuid(uid, uid) < 0)
538 if (cwd && chdir(cwd))
544 box_inside(argc-optind, argv+optind);
547 die("Internal error: fell over edge of the world");