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;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static time_t start_time;
46 static int ticks_per_sec;
48 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
49 /* glibc 2.1 or newer -> has lseek64 */
50 #define long_seek(f,o,w) lseek64(f,o,w)
52 /* Touching clandestine places in glibc */
53 extern loff_t llseek(int fd, loff_t pos, int whence);
54 #define long_seek(f,o,w) llseek(f,o,w)
63 ptrace(PTRACE_KILL, box_pid);
64 kill(-box_pid, SIGKILL);
65 kill(box_pid, SIGKILL);
70 static void NONRET __attribute__((format(printf,1,2)))
75 vfprintf(stderr, msg, args);
80 static void __attribute__((format(printf,1,2)))
87 vfprintf(stderr, msg, args);
94 valid_filename(unsigned long addr)
96 char namebuf[4096], *p, *end;
100 die("File access forbidden.");
101 if (file_access >= 9)
106 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
107 mem_fd = open(namebuf, O_RDONLY);
109 die("open(%s): %m", namebuf);
116 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
117 int l = namebuf + sizeof(namebuf) - end;
121 die("Access to file with name too long.");
122 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
123 die("long_seek(mem): %m");
124 remains = read(mem_fd, end, l);
126 die("read(mem): %m");
128 die("Access to file with name out of memory.");
135 log("[%s] ", namebuf);
136 if (file_access >= 3)
138 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
140 if (file_access >= 2)
142 if ((!strncmp(namebuf, "/etc/", 5) ||
143 !strncmp(namebuf, "/lib/", 5) ||
144 !strncmp(namebuf, "/usr/lib/", 9))
145 && !strstr(namebuf, ".."))
147 if (!strcmp(namebuf, "/dev/null") ||
148 !strcmp(namebuf, "/dev/zero") ||
149 !strcmp(namebuf, "/proc/meminfo") ||
150 !strcmp(namebuf, "/proc/self/stat") ||
151 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
154 die("Forbidden access to file `%s'.", namebuf);
158 valid_syscall(struct user *u)
160 switch (u->regs.orig_eax)
164 static int exec_counter;
165 return !exec_counter++;
179 valid_filename(u->regs.ebx);
197 case SYS_personality:
204 case SYS_ftruncate64:
226 case SYS_gettimeofday:
233 case SYS_sigprocmask:
242 case SYS_rt_sigreturn:
243 case SYS_rt_sigaction:
244 case SYS_rt_sigprocmask:
245 case SYS_rt_sigpending:
246 case SYS_rt_sigtimedwait:
247 case SYS_rt_sigqueueinfo:
248 case SYS_rt_sigsuspend:
251 return (filter_syscalls == 1);
260 signal_alarm(int unused UNUSED)
262 /* Time limit checks are synchronous, so we only schedule them there. */
268 signal_int(int unused UNUSED)
270 /* Interrupts are fatal, so no synchronization requirements. */
280 sec = time(NULL) - start_time;
285 static int proc_status_fd;
288 sprintf(buf, "/proc/%d/stat", (int) box_pid);
289 proc_status_fd = open(buf, O_RDONLY);
290 if (proc_status_fd < 0)
291 die("open(%s): %m", buf);
293 lseek(proc_status_fd, 0, SEEK_SET);
294 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
295 die("read on /proc/$pid/stat: %m");
296 if (c >= (int) sizeof(buf) - 1)
297 die("/proc/$pid/stat too long");
300 while (*x && *x != ' ')
305 die("proc syntax error 1");
306 while (*x && (*x != ')' || x[1] != ' '))
308 while (*x == ')' || *x == ' ')
310 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
311 die("proc syntax error 2");
312 sec = (utime + stime)/ticks_per_sec;
315 fprintf(stderr, "[timecheck: %d seconds]\n", sec);
317 die("Time limit exceeded.");
323 int syscall_count = 0;
327 bzero(&sa, sizeof(sa));
328 sa.sa_handler = signal_int;
329 sigaction(SIGINT, &sa, NULL);
330 start_time = time(NULL);
331 ticks_per_sec = sysconf(_SC_CLK_TCK);
332 if (ticks_per_sec <= 0)
333 die("Invalid ticks_per_sec!");
336 sa.sa_handler = signal_alarm;
337 sigaction(SIGALRM, &sa, NULL);
350 p = wait4(box_pid, &stat, WUNTRACED, &rus);
358 die("wait4: unknown pid %d exited!", p);
361 struct timeval total;
364 if (WEXITSTATUS(stat))
365 die("Exited with error status %d.", WEXITSTATUS(stat));
366 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
367 wall = time(NULL) - start_time;
368 if ((use_wall_clock ? wall : total.tv_sec) > timeout)
369 die("Time limit exceeded (after exit).");
370 fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
373 if (WIFSIGNALED(stat))
376 die("Caught fatal signal %d.", WTERMSIG(stat));
378 if (WIFSTOPPED(stat))
380 int sig = WSTOPSIG(stat);
384 static int stop_count = -1;
385 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
386 die("ptrace(PTRACE_GETREGS): %m");
388 if (!stop_count) /* Traceme request */
389 log(">> Traceme request caught\n");
390 else if (stop_count & 1) /* Syscall entry */
392 log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
394 if (!valid_syscall(&u))
397 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
398 * so we have to change it to something harmless (e.g., an undefined
399 * syscall) and make the program continue.
401 unsigned int sys = u.regs.orig_eax;
402 u.regs.orig_eax = 0xffffffff;
403 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
404 die("ptrace(PTRACE_SETREGS): %m");
405 die("Forbidden syscall %d.", sys);
408 else /* Syscall return */
409 log("= %ld\n", u.regs.eax);
410 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
412 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
414 log(">> Signal %d\n", sig);
415 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
418 die("Received signal %d.", sig);
421 die("wait4: unknown status %x, giving up!", stat);
426 box_inside(int argc, char **argv)
430 char *env[1] = { NULL };
432 memcpy(args, argv, argc * sizeof(char *));
437 if (open(redir_stdin, O_RDONLY) != 0)
438 die("open(\"%s\"): %m", redir_stdin);
443 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
444 die("open(\"%s\"): %m", redir_stdout);
446 if (set_cwd && chdir(set_cwd))
452 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
453 if (setrlimit(RLIMIT_AS, &rl) < 0)
454 die("setrlimit: %m");
456 rl.rlim_cur = rl.rlim_max = 64;
457 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
458 die("setrlimit: %m");
459 if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
460 die("ptrace(PTRACE_TRACEME): %m");
461 execve(args[0], args, (pass_environ ? environ : env));
462 die("execve(\"%s\"): %m", args[0]);
468 fprintf(stderr, "Invalid arguments!\n");
470 Usage: box [<options>] -- <command> <arguments>\n\
473 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
474 -c <dir>\tChange directory to <dir> first\n\
475 -e\t\tPass full environment of parent process\n\
476 -f\t\tFilter system calls (-ff=very restricted)\n\
477 -i <file>\tRedirect stdin from <file>\n\
478 -m <size>\tLimit address space to <size> KB\n\
479 -o <file>\tRedirect stdout to <file>\n\
480 -t <time>\tStop after <time> seconds\n\
481 -T\t\tAllow syscalls for measuring run time\n\
483 -w\t\tMeasure wall clock time instead of run time\n\
489 main(int argc, char **argv)
494 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw")) >= 0)
498 file_access = atol(optarg);
510 redir_stdin = optarg;
513 memory_limit = atol(optarg);
516 redir_stdout = optarg;
519 timeout = atol(optarg);
537 if (setreuid(uid, uid) < 0)
543 box_inside(argc-optind, argv+optind);
546 die("Internal error: fell over edge of the world");