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 char *redir_stdin, *redir_stdout;
41 static int is_ptraced;
42 static volatile int timer_tick;
43 static time_t start_time;
44 static int ticks_per_sec;
46 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
47 /* glibc 2.1 or newer -> has lseek64 */
48 #define long_seek(f,o,w) lseek64(f,o,w)
50 /* Touching clandestine places in glibc */
51 extern loff_t llseek(int fd, loff_t pos, int whence);
52 #define long_seek(f,o,w) llseek(f,o,w)
61 ptrace(PTRACE_KILL, box_pid);
62 kill(-box_pid, SIGKILL);
63 kill(box_pid, SIGKILL);
68 static void NONRET __attribute__((format(printf,1,2)))
73 vfprintf(stderr, msg, args);
78 static void __attribute__((format(printf,1,2)))
85 vfprintf(stderr, msg, args);
92 valid_filename(unsigned long addr)
94 char namebuf[4096], *p, *end;
98 die("File access forbidden.");
104 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
105 mem_fd = open(namebuf, O_RDONLY);
107 die("open(%s): %m", namebuf);
114 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
115 int l = namebuf + sizeof(namebuf) - end;
119 die("Access to file with name too long.");
120 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
121 die("long_seek(mem): %m");
122 remains = read(mem_fd, end, l);
124 die("read(mem): %m");
126 die("Access to file with name out of memory.");
133 log("[%s] ", namebuf);
134 if (file_access >= 3)
136 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
138 if (file_access >= 2)
140 if ((!strncmp(namebuf, "/etc/", 5) ||
141 !strncmp(namebuf, "/lib/", 5) ||
142 !strncmp(namebuf, "/usr/lib/", 9))
143 && !strstr(namebuf, ".."))
145 if (!strcmp(namebuf, "/dev/null") ||
146 !strcmp(namebuf, "/dev/zero"))
149 die("Forbidden access to file `%s'.", namebuf);
153 valid_syscall(struct user *u)
155 switch (u->regs.orig_eax)
159 static int exec_counter;
160 return !exec_counter++;
174 valid_filename(u->regs.ebx);
192 case SYS_personality:
199 case SYS_ftruncate64:
219 case SYS_gettimeofday:
226 case SYS_sigprocmask:
234 case SYS_rt_sigreturn:
235 case SYS_rt_sigaction:
236 case SYS_rt_sigprocmask:
237 case SYS_rt_sigpending:
238 case SYS_rt_sigtimedwait:
239 case SYS_rt_sigqueueinfo:
240 case SYS_rt_sigsuspend:
242 return (filter_syscalls == 1);
249 signal_alarm(int unused UNUSED)
251 /* Time limit checks are synchronous, so we only schedule them there. */
257 signal_int(int unused UNUSED)
259 /* Interrupts are fatal, so no synchronization requirements. */
269 sec = time(NULL) - start_time;
274 static int proc_status_fd;
277 sprintf(buf, "/proc/%d/stat", (int) box_pid);
278 proc_status_fd = open(buf, O_RDONLY);
279 if (proc_status_fd < 0)
280 die("open(%s): %m", buf);
282 lseek(proc_status_fd, 0, SEEK_SET);
283 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
284 die("read on /proc/$pid/stat: %m");
285 if (c >= (int) sizeof(buf) - 1)
286 die("/proc/$pid/stat too long");
289 while (*x && *x != ' ')
294 die("proc syntax error 1");
295 while (*x && (*x != ')' || x[1] != ' '))
297 while (*x == ')' || *x == ' ')
299 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
300 die("proc syntax error 2");
301 sec = (utime + stime)/ticks_per_sec;
304 fprintf(stderr, "[timecheck: %d seconds]\n", sec);
306 die("Time limit exceeded.");
312 int syscall_count = 0;
316 bzero(&sa, sizeof(sa));
317 sa.sa_handler = signal_int;
318 sigaction(SIGINT, &sa, NULL);
319 start_time = time(NULL);
320 ticks_per_sec = sysconf(_SC_CLK_TCK);
321 if (ticks_per_sec <= 0)
322 die("Invalid ticks_per_sec!");
325 sa.sa_handler = signal_alarm;
326 sigaction(SIGALRM, &sa, NULL);
339 p = wait4(box_pid, &stat, WUNTRACED, &rus);
347 die("wait4: unknown pid %d exited!", p);
350 struct timeval total;
353 if (WEXITSTATUS(stat))
354 die("Exited with error status %d.", WEXITSTATUS(stat));
355 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
356 wall = time(NULL) - start_time;
357 if ((use_wall_clock ? wall : total.tv_sec) > timeout)
358 die("Timeout exceeded (after exit).");
359 fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
362 if (WIFSIGNALED(stat))
365 die("Caught fatal signal %d.", WTERMSIG(stat));
367 if (WIFSTOPPED(stat))
369 int sig = WSTOPSIG(stat);
373 static int stop_count = -1;
374 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
375 die("ptrace(PTRACE_GETREGS): %m");
377 if (!stop_count) /* Traceme request */
378 log(">> Traceme request caught\n");
379 else if (stop_count & 1) /* Syscall entry */
381 log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
383 if (!valid_syscall(&u))
386 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
387 * so we have to change it to something harmless (e.g., an undefined
388 * syscall) and make the program continue.
390 unsigned int sys = u.regs.orig_eax;
391 u.regs.orig_eax = 0xffffffff;
392 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
393 die("ptrace(PTRACE_SETREGS): %m");
394 die("Forbidden syscall %d.", sys);
397 else /* Syscall return */
398 log("= %ld\n", u.regs.eax);
399 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
401 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
403 log(">> Signal %d\n", sig);
404 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
407 die("Received signal %d.", sig);
410 die("wait4: unknown status %x, giving up!", stat);
415 box_inside(int argc, char **argv)
419 char *env[1] = { NULL };
421 memcpy(args, argv, argc * sizeof(char *));
426 if (open(redir_stdin, O_RDONLY) != 0)
427 die("open(\"%s\"): %m", redir_stdin);
432 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
433 die("open(\"%s\"): %m", redir_stdout);
440 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
441 if (setrlimit(RLIMIT_AS, &rl) < 0)
442 die("setrlimit: %m");
444 rl.rlim_cur = rl.rlim_max = 64;
445 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
446 die("setrlimit: %m");
447 if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
448 die("ptrace(PTRACE_TRACEME): %m");
449 execve(args[0], args, (pass_environ ? environ : env));
450 die("execve(\"%s\"): %m", args[0]);
456 fprintf(stderr, "Invalid arguments!\n");
458 Usage: box [<options>] -- <command> <arguments>\n\
461 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
462 -c <dir>\tChange directory to <dir> first\n\
463 -e\t\tPass full environment of parent process\n\
464 -f\t\tFilter system calls (-ff=very restricted)\n\
465 -i <file>\tRedirect stdin from <file>\n\
466 -m <size>\tLimit address space to <size> KB\n\
467 -o <file>\tRedirect stdout to <file>\n\
468 -t <time>\tStop after <time> seconds\n\
470 -w\t\tMeasure wall clock time instead of run time\n\
476 main(int argc, char **argv)
482 while ((c = getopt(argc, argv, "a:c:efi:m:o:t:vw")) >= 0)
486 file_access = atol(optarg);
498 redir_stdin = optarg;
501 memory_limit = atol(optarg);
504 redir_stdout = optarg;
507 timeout = atol(optarg);
522 if (setreuid(uid, uid) < 0)
524 if (cwd && chdir(cwd))
530 box_inside(argc-optind, argv+optind);
533 die("Internal error: fell over edge of the world");