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;
40 static int is_ptraced;
41 static volatile int timer_tick;
42 static time_t start_time;
43 static int ticks_per_sec;
45 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
46 /* glibc 2.1 or newer -> has lseek64 */
47 #define long_seek(f,o,w) lseek64(f,o,w)
49 /* Touching clandestine places in glibc */
50 extern loff_t llseek(int fd, loff_t pos, int whence);
51 #define long_seek(f,o,w) llseek(f,o,w)
60 ptrace(PTRACE_KILL, box_pid);
61 kill(-box_pid, SIGKILL);
62 kill(box_pid, SIGKILL);
67 static void NONRET __attribute__((format(printf,1,2)))
72 vfprintf(stderr, msg, args);
77 static void __attribute__((format(printf,1,2)))
84 vfprintf(stderr, msg, args);
91 valid_filename(unsigned long addr)
93 char namebuf[4096], *p, *end;
97 die("File access forbidden.");
103 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
104 mem_fd = open(namebuf, O_RDONLY);
106 die("open(%s): %m", namebuf);
113 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
114 int l = namebuf + sizeof(namebuf) - end;
118 die("Access to file with name too long.");
119 if (long_seek(mem_fd, addr, SEEK_SET) < 0)
120 die("long_seek(mem): %m");
121 remains = read(mem_fd, end, l);
123 die("read(mem): %m");
125 die("Access to file with name out of memory.");
132 log("[%s] ", namebuf);
133 if (file_access >= 3)
135 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
137 if (file_access >= 2)
139 if ((!strncmp(namebuf, "/etc/", 5) ||
140 !strncmp(namebuf, "/lib/", 5) ||
141 !strncmp(namebuf, "/usr/lib/", 9))
142 && !strstr(namebuf, ".."))
144 if (!strcmp(namebuf, "/dev/null") ||
145 !strcmp(namebuf, "/dev/zero"))
148 die("Forbidden access to file `%s'.", namebuf);
152 valid_syscall(struct user *u)
154 switch (u->regs.orig_eax)
158 static int exec_counter;
159 return !exec_counter++;
173 valid_filename(u->regs.ebx);
191 case SYS_personality:
198 case SYS_ftruncate64:
217 case SYS_gettimeofday:
224 case SYS_sigprocmask:
232 case SYS_rt_sigreturn:
233 case SYS_rt_sigaction:
234 case SYS_rt_sigprocmask:
235 case SYS_rt_sigpending:
236 case SYS_rt_sigtimedwait:
237 case SYS_rt_sigqueueinfo:
238 case SYS_rt_sigsuspend:
240 return (filter_syscalls == 1);
247 signal_alarm(int unused UNUSED)
249 /* Time limit checks are synchronous, so we only schedule them there. */
255 signal_int(int unused UNUSED)
257 /* Interrupts are fatal, so no synchronization requirements. */
267 sec = time(NULL) - start_time;
272 static int proc_status_fd;
275 sprintf(buf, "/proc/%d/stat", (int) box_pid);
276 proc_status_fd = open(buf, O_RDONLY);
277 if (proc_status_fd < 0)
278 die("open(%s): %m", buf);
280 lseek(proc_status_fd, 0, SEEK_SET);
281 if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
282 die("read on /proc/$pid/stat: %m");
283 if (c >= (int) sizeof(buf) - 1)
284 die("/proc/$pid/stat too long");
287 while (*x && *x != ' ')
292 die("proc syntax error 1");
293 while (*x && (*x != ')' || x[1] != ' '))
295 while (*x == ')' || *x == ' ')
297 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
298 die("proc syntax error 2");
299 sec = (utime + stime)/ticks_per_sec;
302 fprintf(stderr, "[timecheck: %d seconds]\n", sec);
304 die("Time limit exceeded.");
310 int syscall_count = 0;
314 bzero(&sa, sizeof(sa));
315 sa.sa_handler = signal_int;
316 sigaction(SIGINT, &sa, NULL);
317 start_time = time(NULL);
318 ticks_per_sec = sysconf(_SC_CLK_TCK);
319 if (ticks_per_sec <= 0)
320 die("Invalid ticks_per_sec!");
323 sa.sa_handler = signal_alarm;
324 sigaction(SIGALRM, &sa, NULL);
337 p = wait4(box_pid, &stat, WUNTRACED, &rus);
345 die("wait4: unknown pid %d exited!", p);
348 struct timeval total;
351 if (WEXITSTATUS(stat))
352 die("Exited with error status %d.", WEXITSTATUS(stat));
353 timeradd(&rus.ru_utime, &rus.ru_stime, &total);
354 wall = time(NULL) - start_time;
355 if ((use_wall_clock ? wall : total.tv_sec) > timeout)
356 die("Timeout exceeded (after exit).");
357 fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
360 if (WIFSIGNALED(stat))
363 die("Caught fatal signal %d.", WTERMSIG(stat));
365 if (WIFSTOPPED(stat))
367 int sig = WSTOPSIG(stat);
371 static int stop_count = -1;
372 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
373 die("ptrace(PTRACE_GETREGS): %m");
375 if (!stop_count) /* Traceme request */
376 log(">> Traceme request caught\n");
377 else if (stop_count & 1) /* Syscall entry */
379 log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
381 if (!valid_syscall(&u))
384 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
385 * so we have to change it to something harmless (e.g., an undefined
386 * syscall) and make the program continue.
388 unsigned int sys = u.regs.orig_eax;
389 u.regs.orig_eax = 0xffffffff;
390 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
391 die("ptrace(PTRACE_SETREGS): %m");
392 die("Forbidden syscall %d.", sys);
395 else /* Syscall return */
396 log("= %ld\n", u.regs.eax);
397 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
399 else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
401 log(">> Signal %d\n", sig);
402 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
405 die("Received signal %d.", sig);
408 die("wait4: unknown status %x, giving up!", stat);
413 box_inside(int argc, char **argv)
417 char *env[1] = { NULL };
419 memcpy(args, argv, argc * sizeof(char *));
426 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
427 if (setrlimit(RLIMIT_AS, &rl) < 0)
428 die("setrlimit: %m");
430 rl.rlim_cur = rl.rlim_max = 64;
431 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
432 die("setrlimit: %m");
433 if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
434 die("ptrace(PTRACE_TRACEME): %m");
435 execve(args[0], args, (pass_environ ? environ : env));
436 die("execve(\"%s\"): %m", args[0]);
442 fprintf(stderr, "Invalid arguments!\n");
444 Usage: box [<options>] -- <command> <arguments>\n\
447 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
448 -c <dir>\tChange directory to <dir> first\n\
449 -e\t\tPass full environment of parent process\n\
450 -f\t\tFilter system calls (-ff=very restricted)\n\
451 -m <size>\tLimit address space to <size> KB\n\
452 -t <time>\tStop after <time> seconds\n\
454 -w\t\tMeasure wall clock time instead of run time\n\
460 main(int argc, char **argv)
466 while ((c = getopt(argc, argv, "a:c:efm:t:vw")) >= 0)
470 file_access = atol(optarg);
482 memory_limit = atol(optarg);
485 timeout = atol(optarg);
500 if (setreuid(uid, uid) < 0)
502 if (cwd && chdir(cwd))
508 box_inside(argc-optind, argv+optind);
511 die("Internal error: fell over edge of the world");