2 * A Simple Testing Sandbox
4 * (c) 2001--2004 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 !strncmp(namebuf, "/opt/lib/", 9))
146 && !strstr(namebuf, ".."))
148 if (!strcmp(namebuf, "/dev/null") ||
149 !strcmp(namebuf, "/dev/zero") ||
150 !strcmp(namebuf, "/proc/meminfo") ||
151 !strcmp(namebuf, "/proc/self/stat") ||
152 !strcmp(namebuf, "/proc/self/exe") || /* Needed by FPC 2.0.x runtime */
153 !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
156 die("Forbidden access to file `%s'.", namebuf);
160 valid_syscall(struct user *u)
162 switch (u->regs.orig_eax)
166 static int exec_counter;
167 return !exec_counter++;
178 case __NR_truncate64:
182 valid_filename(u->regs.ebx);
200 case __NR_personality:
212 case __NR_ftruncate64:
221 case __NR_set_thread_area:
222 case __NR_get_thread_area:
223 case __NR_exit_group:
233 case __NR_sigsuspend:
234 case __NR_sigpending:
237 case __NR_gettimeofday:
244 case __NR_sigprocmask:
246 case __NR_getdents64:
247 case __NR__newselect:
253 case __NR_rt_sigreturn:
254 case __NR_rt_sigaction:
255 case __NR_rt_sigprocmask:
256 case __NR_rt_sigpending:
257 case __NR_rt_sigtimedwait:
258 case __NR_rt_sigqueueinfo:
259 case __NR_rt_sigsuspend:
262 return (filter_syscalls == 1);
266 if (u->regs.ebx == box_pid)
267 die("Commited suicide by signal %d.", (int)u->regs.ecx);
270 if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
271 die("Commited suicide by signal %d.", (int)u->regs.edx);
279 signal_alarm(int unused UNUSED)
281 /* Time limit checks are synchronous, so we only schedule them there. */
287 signal_int(int unused UNUSED)
289 /* Interrupts are fatal, so no synchronization requirements. */
299 sec = time(NULL) - start_time;
304 static int proc_status_fd;
307 sprintf(buf, "/proc/%d/stat", (int) box_pid);
308 proc_status_fd = open(buf, O_RDONLY);
309 if (proc_status_fd < 0)
310 die("open(%s): %m", buf);
312 lseek(proc_status_fd, 0, SEEK_SET);
313 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
314 die("read on /proc/$pid/stat: %m");
315 if (c >= (int) sizeof(buf) - 1)
316 die("/proc/$pid/stat too long");
319 while (*x && *x != ' ')
324 die("proc syntax error 1");
325 while (*x && (*x != ')' || x[1] != ' '))
327 while (*x == ')' || *x == ' ')
329 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
330 die("proc syntax error 2");
331 sec = (utime + stime)/ticks_per_sec;
334 fprintf(stderr, "[timecheck: %d seconds]\n", sec);
336 die("Time limit exceeded.");
342 int syscall_count = 0;
346 bzero(&sa, sizeof(sa));
347 sa.sa_handler = signal_int;
348 sigaction(SIGINT, &sa, NULL);
349 start_time = time(NULL);
350 ticks_per_sec = sysconf(_SC_CLK_TCK);
351 if (ticks_per_sec <= 0)
352 die("Invalid ticks_per_sec!");
355 sa.sa_handler = signal_alarm;
356 sigaction(SIGALRM, &sa, NULL);
369 p = wait4(box_pid, &stat, WUNTRACED, &rus);
377 die("wait4: unknown pid %d exited!", p);
380 struct timeval total;
383 if (WEXITSTATUS(stat))
384 die("Exited with error status %d.", WEXITSTATUS(stat));
385 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
386 wall = time(NULL) - start_time;
387 if ((use_wall_clock ? wall : total.tv_sec) > timeout)
388 die("Time limit exceeded (after exit).");
389 fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
392 if (WIFSIGNALED(stat))
395 die("Caught fatal signal %d.", WTERMSIG(stat));
397 if (WIFSTOPPED(stat))
399 int sig = WSTOPSIG(stat);
403 static int stop_count = -1;
404 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
405 die("ptrace(PTRACE_GETREGS): %m");
407 if (!stop_count) /* Traceme request */
408 log(">> Traceme request caught\n");
409 else if (stop_count & 1) /* Syscall entry */
411 log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
413 if (!valid_syscall(&u))
416 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
417 * so we have to change it to something harmless (e.g., an undefined
418 * syscall) and make the program continue.
420 unsigned int sys = u.regs.orig_eax;
421 u.regs.orig_eax = 0xffffffff;
422 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
423 die("ptrace(PTRACE_SETREGS): %m");
424 die("Forbidden syscall %d.", sys);
427 else /* Syscall return */
428 log("= %ld\n", u.regs.eax);
429 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
431 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
433 log(">> Signal %d\n", sig);
434 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
437 die("Received signal %d.", sig);
440 die("wait4: unknown status %x, giving up!", stat);
445 box_inside(int argc, char **argv)
449 char *env[1] = { NULL };
451 memcpy(args, argv, argc * sizeof(char *));
453 if (set_cwd && chdir(set_cwd))
458 if (open(redir_stdin, O_RDONLY) != 0)
459 die("open(\"%s\"): %m", redir_stdin);
464 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
465 die("open(\"%s\"): %m", redir_stdout);
471 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
472 if (setrlimit(RLIMIT_AS, &rl) < 0)
473 die("setrlimit: %m");
475 rl.rlim_cur = rl.rlim_max = 64;
476 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
477 die("setrlimit: %m");
478 if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
479 die("ptrace(PTRACE_TRACEME): %m");
480 execve(args[0], args, (pass_environ ? environ : env));
481 die("execve(\"%s\"): %m", args[0]);
487 fprintf(stderr, "Invalid arguments!\n");
489 Usage: box [<options>] -- <command> <arguments>\n\
492 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
493 -c <dir>\tChange directory to <dir> first\n\
494 -e\t\tPass full environment of parent process\n\
495 -f\t\tFilter system calls (-ff=very restricted)\n\
496 -i <file>\tRedirect stdin from <file>\n\
497 -m <size>\tLimit address space to <size> KB\n\
498 -o <file>\tRedirect stdout to <file>\n\
499 -t <time>\tStop after <time> seconds\n\
500 -T\t\tAllow syscalls for measuring run time\n\
502 -w\t\tMeasure wall clock time instead of run time\n\
508 main(int argc, char **argv)
513 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw")) >= 0)
517 file_access = atol(optarg);
529 redir_stdin = optarg;
532 memory_limit = atol(optarg);
535 redir_stdout = optarg;
538 timeout = atol(optarg);
556 if (setreuid(uid, uid) < 0)
562 box_inside(argc-optind, argv+optind);
565 die("Internal error: fell over edge of the world");