]> mj.ucw.cz Git - eval.git/blob - src/box.c
fe1c22f83a7e81bd068a0a0dcab63666666671c2
[eval.git] / src / box.c
1 /*
2  *      A Simple Testing Sandbox
3  *
4  *      (c) 2001--2007 Martin Mares <mj@ucw.cz>
5  */
6
7 #define _LARGEFILE64_SOURCE
8 #define _GNU_SOURCE
9
10 #include <errno.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <stdarg.h>
16 #include <unistd.h>
17 #include <getopt.h>
18 #include <time.h>
19 #include <sys/wait.h>
20 #include <sys/user.h>
21 #include <sys/time.h>
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>
27
28 #define NONRET __attribute__((noreturn))
29 #define UNUSED __attribute__((unused))
30
31 static int filter_syscalls;             /* 0=off, 1=liberal, 2=totalitarian */
32 static int timeout;                     /* milliseconds */
33 static int wall_timeout;
34 static int pass_environ;
35 static int file_access;
36 static int verbose;
37 static int memory_limit;
38 static int allow_times;
39 static char *redir_stdin, *redir_stdout;
40 static char *set_cwd;
41
42 static pid_t box_pid;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static struct timeval start_time;
46 static int ticks_per_sec;
47 static int exec_seen;
48
49 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
50 /* glibc 2.1 or newer -> has lseek64 */
51 #define long_seek(f,o,w) lseek64(f,o,w)
52 #else
53 /* Touching clandestine places in glibc */
54 extern loff_t llseek(int fd, loff_t pos, int whence);
55 #define long_seek(f,o,w) llseek(f,o,w)
56 #endif
57
58 static void NONRET
59 box_exit(void)
60 {
61   if (box_pid > 0)
62     {
63       if (is_ptraced)
64         ptrace(PTRACE_KILL, box_pid);
65       kill(-box_pid, SIGKILL);
66       kill(box_pid, SIGKILL);
67     }
68   exit(1);
69 }
70
71 static void NONRET __attribute__((format(printf,1,2)))
72 die(char *msg, ...)
73 {
74   va_list args;
75   va_start(args, msg);
76   vfprintf(stderr, msg, args);
77   fputc('\n', stderr);
78   box_exit();
79 }
80
81 static void __attribute__((format(printf,1,2)))
82 msg(char *msg, ...)
83 {
84   va_list args;
85   va_start(args, msg);
86   if (verbose)
87     {
88       vfprintf(stderr, msg, args);
89       fflush(stderr);
90     }
91   va_end(args);
92 }
93
94 struct syscall {
95   const char *name;
96   int override;
97 };
98
99 static struct syscall syscall_tab[] = {
100 #include "syscall-table.h"
101 };
102 #define NUM_SYSCALLS (sizeof(syscall_tab)/sizeof(syscall_tab[0]))
103
104 static const char *
105 syscall_name(unsigned int id, char *buf)
106 {
107   if (id < NUM_SYSCALLS && syscall_tab[id].name)
108     return syscall_tab[id].name;
109   else
110     {
111       sprintf(buf, "#%d", id);
112       return buf;
113     }
114 }
115
116 #if 0
117 static struct syscall *
118 syscall_by_name(char *name)
119 {
120   for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
121     if (!strcmp(syscall_tab[i].name, name))
122       return &syscall_tab[i];
123   return NULL;
124 }
125 #endif
126
127 static void
128 valid_filename(unsigned long addr)
129 {
130   char namebuf[4096], *p, *end;
131   static int mem_fd;
132
133   if (!file_access)
134     die("File access forbidden");
135   if (file_access >= 9)
136     return;
137
138   if (!mem_fd)
139     {
140       sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
141       mem_fd = open(namebuf, O_RDONLY);
142       if (mem_fd < 0)
143         die("open(%s): %m", namebuf);
144     }
145   p = end = namebuf;
146   do
147     {
148       if (p >= end)
149         {
150           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
151           int l = namebuf + sizeof(namebuf) - end;
152           if (l > remains)
153             l = remains;
154           if (!l)
155             die("Access to file with name too long");
156           if (long_seek(mem_fd, addr, SEEK_SET) < 0)
157             die("long_seek(mem): %m");
158           remains = read(mem_fd, end, l);
159           if (remains < 0)
160             die("read(mem): %m");
161           if (!remains)
162             die("Access to file with name out of memory");
163           end += l;
164           addr += l;
165         }
166     }
167   while (*p++);
168
169   msg("[%s] ", namebuf);
170   if (file_access >= 3)
171     return;
172   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
173     return;
174   if (file_access >= 2)
175     {
176       if ((!strncmp(namebuf, "/etc/", 5) ||
177            !strncmp(namebuf, "/lib/", 5) ||
178            !strncmp(namebuf, "/usr/lib/", 9) ||
179            !strncmp(namebuf, "/opt/lib/", 9))
180           && !strstr(namebuf, ".."))
181         return;
182       if (!strcmp(namebuf, "/dev/null") ||
183           !strcmp(namebuf, "/dev/zero") ||
184           !strcmp(namebuf, "/proc/meminfo") ||
185           !strcmp(namebuf, "/proc/self/stat") ||
186           !strcmp(namebuf, "/proc/self/exe") ||                 /* Needed by FPC 2.0.x runtime */
187           !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
188         return;
189     }
190   die("Forbidden access to file `%s'", namebuf);
191 }
192
193 static int
194 valid_syscall(struct user *u)
195 {
196   switch (u->regs.orig_eax)
197     {
198     case __NR_open:
199     case __NR_creat:
200     case __NR_unlink:
201     case __NR_oldstat:
202     case __NR_access:                   
203     case __NR_oldlstat:                 
204     case __NR_truncate:
205     case __NR_stat:
206     case __NR_lstat:
207     case __NR_truncate64:
208     case __NR_stat64:
209     case __NR_lstat64:
210     case __NR_readlink:
211       valid_filename(u->regs.ebx);
212       return 1;
213     case __NR_exit:
214     case __NR_read:
215     case __NR_write:
216     case __NR_close:
217     case __NR_lseek:
218     case __NR_getpid:
219     case __NR_getuid:
220     case __NR_oldfstat:
221     case __NR_dup:
222     case __NR_brk:
223     case __NR_getgid:
224     case __NR_geteuid:
225     case __NR_getegid:
226     case __NR_dup2:
227     case __NR_ftruncate:
228     case __NR_fstat:
229     case __NR_personality:
230     case __NR__llseek:
231     case __NR_readv:
232     case __NR_writev:
233     case __NR_getresuid:
234 #ifdef __NR_pread64
235     case __NR_pread64:
236     case __NR_pwrite64:
237 #else
238     case __NR_pread:
239     case __NR_pwrite:
240 #endif
241     case __NR_ftruncate64:
242     case __NR_fstat64:
243     case __NR_fcntl:
244     case __NR_fcntl64:
245     case __NR_mmap:
246     case __NR_munmap:
247     case __NR_ioctl:
248     case __NR_uname:
249     case __NR_gettid:
250     case __NR_set_thread_area:
251     case __NR_get_thread_area:
252     case __NR_exit_group:
253       return 1;
254     case __NR_time:
255     case __NR_alarm:
256     case __NR_pause:
257     case __NR_signal:
258     case __NR_fchmod:
259     case __NR_sigaction:
260     case __NR_sgetmask:
261     case __NR_ssetmask:
262     case __NR_sigsuspend:
263     case __NR_sigpending:
264     case __NR_getrlimit:
265     case __NR_getrusage:
266     case __NR_gettimeofday:
267     case __NR_select:
268     case __NR_readdir:
269     case __NR_setitimer:
270     case __NR_getitimer:
271     case __NR_sigreturn:
272     case __NR_mprotect:
273     case __NR_sigprocmask:
274     case __NR_getdents:
275     case __NR_getdents64:
276     case __NR__newselect:
277     case __NR_fdatasync:
278     case __NR_mremap:
279     case __NR_poll:
280     case __NR_getcwd:
281     case __NR_nanosleep:
282     case __NR_rt_sigreturn:
283     case __NR_rt_sigaction:
284     case __NR_rt_sigprocmask:
285     case __NR_rt_sigpending:
286     case __NR_rt_sigtimedwait:
287     case __NR_rt_sigqueueinfo:
288     case __NR_rt_sigsuspend:
289     case __NR_mmap2:
290     case __NR__sysctl:
291       return (filter_syscalls == 1);
292     case __NR_times:
293       return allow_times;
294     case __NR_kill:
295       if (u->regs.ebx == box_pid)
296         die("Committed suicide by signal %d", (int)u->regs.ecx);
297       return 0;
298     case __NR_tgkill:
299       if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
300         die("Committed suicide by signal %d", (int)u->regs.edx);
301       return 0;
302     default:
303       return 0;
304     }
305 }
306
307 static void
308 signal_alarm(int unused UNUSED)
309 {
310   /* Time limit checks are synchronous, so we only schedule them there. */
311   timer_tick = 1;
312   alarm(1);
313 }
314
315 static void
316 signal_int(int unused UNUSED)
317 {
318   /* Interrupts are fatal, so no synchronization requirements. */
319   die("Interrupted");
320 }
321
322 static void
323 check_timeout(void)
324 {
325   if (wall_timeout)
326     {
327       struct timeval now, wall;
328       int wall_ms;
329       gettimeofday(&now, NULL);
330       timersub(&now, &start_time, &wall);
331       wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
332       if (wall_ms > wall_timeout)
333         die("Time limit exceeded (wall clock)");
334       if (verbose > 1)
335         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
336     }
337   if (timeout)
338     {
339       char buf[4096], *x;
340       int c, utime, stime, ms;
341       static int proc_status_fd;
342       if (!proc_status_fd)
343         {
344           sprintf(buf, "/proc/%d/stat", (int) box_pid);
345           proc_status_fd = open(buf, O_RDONLY);
346           if (proc_status_fd < 0)
347             die("open(%s): %m", buf);
348         }
349       lseek(proc_status_fd, 0, SEEK_SET);
350       if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
351         die("read on /proc/$pid/stat: %m");
352       if (c >= (int) sizeof(buf) - 1)
353         die("/proc/$pid/stat too long");
354       buf[c] = 0;
355       x = buf;
356       while (*x && *x != ' ')
357         x++;
358       while (*x == ' ')
359         x++;
360       if (*x++ != '(')
361         die("proc syntax error 1");
362       while (*x && (*x != ')' || x[1] != ' '))
363         x++;
364       while (*x == ')' || *x == ' ')
365         x++;
366       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
367         die("proc syntax error 2");
368       ms = (utime + stime) * 1000 / ticks_per_sec;
369       if (verbose > 1)
370         fprintf(stderr, "[time check: %d msec]\n", ms);
371       if (ms > timeout)
372         die("Time limit exceeded");
373     }
374 }
375
376 static void
377 boxkeeper(void)
378 {
379   int syscall_count = 0;
380   struct sigaction sa;
381
382   is_ptraced = 1;
383   bzero(&sa, sizeof(sa));
384   sa.sa_handler = signal_int;
385   sigaction(SIGINT, &sa, NULL);
386   gettimeofday(&start_time, NULL);
387   ticks_per_sec = sysconf(_SC_CLK_TCK);
388   if (ticks_per_sec <= 0)
389     die("Invalid ticks_per_sec!");
390   if (timeout || wall_timeout)
391     {
392       sa.sa_handler = signal_alarm;
393       sigaction(SIGALRM, &sa, NULL);
394       alarm(1);
395     }
396   for(;;)
397     {
398       struct rusage rus;
399       int stat;
400       pid_t p;
401       if (timer_tick)
402         {
403           check_timeout();
404           timer_tick = 0;
405         }
406       p = wait4(box_pid, &stat, WUNTRACED, &rus);
407       if (p < 0)
408         {
409           if (errno == EINTR)
410             continue;
411           die("wait4: %m");
412         }
413       if (p != box_pid)
414         die("wait4: unknown pid %d exited!", p);
415       if (WIFEXITED(stat))
416         {
417           struct timeval total, now, wall;
418           int total_ms, wall_ms;
419           box_pid = 0;
420           if (WEXITSTATUS(stat))
421             die("Exited with error status %d", WEXITSTATUS(stat));
422           timeradd(&rus.ru_utime, &rus.ru_stime, &total);
423           total_ms = total.tv_sec*1000 + total.tv_usec/1000;
424           gettimeofday(&now, NULL);
425           timersub(&now, &start_time, &wall);
426           wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
427           if (timeout && total_ms > timeout)
428             die("Time limit exceeded");
429           if (wall_timeout && wall_ms > wall_timeout)
430             die("Time limit exceeded (wall clock)");
431           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
432               (int) total.tv_sec, (int) total.tv_usec/1000,
433               (int) wall.tv_sec, (int) wall.tv_usec/1000,
434               syscall_count);
435           exit(0);
436         }
437       if (WIFSIGNALED(stat))
438         {
439           box_pid = 0;
440           die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
441         }
442       if (WIFSTOPPED(stat))
443         {
444           int sig = WSTOPSIG(stat);
445           if (sig == SIGTRAP)
446             {
447               struct user u;
448               static int stop_count = -1;
449               if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
450                 die("ptrace(PTRACE_GETREGS): %m");
451               stop_count++;
452               if (!stop_count)                  /* Traceme request */
453                 msg(">> Traceme request caught\n");
454               else if (stop_count & 1)          /* Syscall entry */
455                 {
456                   char namebuf[32];
457                   msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
458                   if (!exec_seen)
459                     {
460                       msg("[master] ");
461                       if (u.regs.orig_eax == __NR_execve)
462                         exec_seen = 1;
463                     }
464                   else if (valid_syscall(&u))
465                     syscall_count++;
466                   else
467                     {
468                       /*
469                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
470                        * so we have to change it to something harmless (e.g., an undefined
471                        * syscall) and make the program continue.
472                        */
473                       unsigned int sys = u.regs.orig_eax;
474                       u.regs.orig_eax = 0xffffffff;
475                       if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
476                         die("ptrace(PTRACE_SETREGS): %m");
477                       die("Forbidden syscall %s", syscall_name(sys, namebuf));
478                     }
479                 }
480               else                                      /* Syscall return */
481                 msg("= %ld\n", u.regs.eax);
482               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
483             }
484           else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
485             {
486               msg(">> Signal %d\n", sig);
487               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
488             }
489           else
490             die("Received signal %d", sig);
491         }
492       else
493         die("wait4: unknown status %x, giving up!", stat);
494     }
495 }
496
497 static void
498 box_inside(int argc, char **argv)
499 {
500   struct rlimit rl;
501   char *args[argc+1];
502   char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
503
504   memcpy(args, argv, argc * sizeof(char *));
505   args[argc] = NULL;
506   if (set_cwd && chdir(set_cwd))
507     die("chdir: %m");
508   if (redir_stdin)
509     {
510       close(0);
511       if (open(redir_stdin, O_RDONLY) != 0)
512         die("open(\"%s\"): %m", redir_stdin);
513     }
514   if (redir_stdout)
515     {
516       close(1);
517       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
518         die("open(\"%s\"): %m", redir_stdout);
519     }
520   dup2(1, 2);
521   setpgrp();
522   if (memory_limit)
523     {
524       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
525       if (setrlimit(RLIMIT_AS, &rl) < 0)
526         die("setrlimit: %m");
527     }
528   rl.rlim_cur = rl.rlim_max = 64;
529   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
530     die("setrlimit: %m");
531   if (filter_syscalls)
532     {
533       if (ptrace(PTRACE_TRACEME) < 0)
534         die("ptrace(PTRACE_TRACEME): %m");
535       /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
536       signal(SIGCHLD, SIG_IGN);
537       raise(SIGCHLD);
538     }
539   execve(args[0], args, (pass_environ ? environ : env));
540   die("execve(\"%s\"): %m", args[0]);
541 }
542
543 static void
544 usage(void)
545 {
546   fprintf(stderr, "Invalid arguments!\n");
547   printf("\
548 Usage: box [<options>] -- <command> <arguments>\n\
549 \n\
550 Options:\n\
551 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
552 -c <dir>\tChange directory to <dir> first\n\
553 -e\t\tPass full environment of parent process\n\
554 -f\t\tFilter system calls (-ff=very restricted)\n\
555 -i <file>\tRedirect stdin from <file>\n\
556 -m <size>\tLimit address space to <size> KB\n\
557 -o <file>\tRedirect stdout to <file>\n\
558 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
559 -T\t\tAllow syscalls for measuring run time\n\
560 -v\t\tBe verbose\n\
561 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
562 ");
563   exit(1);
564 }
565
566 int
567 main(int argc, char **argv)
568 {
569   int c;
570   uid_t uid;
571
572   while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw:")) >= 0)
573     switch (c)
574       {
575       case 'a':
576         file_access = atol(optarg);
577         break;
578       case 'c':
579         set_cwd = optarg;
580         break;
581       case 'e':
582         pass_environ = 1;
583         break;
584       case 'f':
585         filter_syscalls++;
586         break;
587       case 'i':
588         redir_stdin = optarg;
589         break;
590       case 'm':
591         memory_limit = atol(optarg);
592         break;
593       case 'o':
594         redir_stdout = optarg;
595         break;
596       case 't':
597         timeout = 1000*atof(optarg);
598         break;
599       case 'T':
600         allow_times++;
601         break;
602       case 'v':
603         verbose++;
604         break;
605       case 'w':
606         wall_timeout = 1000*atof(optarg);
607         break;
608       default:
609         usage();
610       }
611   if (optind >= argc)
612     usage();
613
614   uid = geteuid();
615   if (setreuid(uid, uid) < 0)
616     die("setreuid: %m");
617   box_pid = fork();
618   if (box_pid < 0)
619     die("fork: %m");
620   if (!box_pid)
621     box_inside(argc-optind, argv+optind);
622   else
623     boxkeeper();
624   die("Internal error: fell over edge of the world");
625 }