]> mj.ucw.cz Git - eval.git/blob - src/box.c
c80fe3d5e26dec0fff906b5baa7cb4e06941e803
[eval.git] / src / box.c
1 /*
2  *      A Simple Sandbox for MO-Eval
3  *
4  *      (c) 2001--2008 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 char *redir_stdin, *redir_stdout;
39 static char *set_cwd;
40
41 static pid_t box_pid;
42 static int is_ptraced;
43 static volatile int timer_tick;
44 static struct timeval start_time;
45 static int ticks_per_sec;
46 static int exec_seen;
47
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)
51 #else
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)
55 #endif
56
57 static void NONRET
58 box_exit(void)
59 {
60   if (box_pid > 0)
61     {
62       if (is_ptraced)
63         ptrace(PTRACE_KILL, box_pid);
64       kill(-box_pid, SIGKILL);
65       kill(box_pid, SIGKILL);
66     }
67   exit(1);
68 }
69
70 static void NONRET __attribute__((format(printf,1,2)))
71 die(char *msg, ...)
72 {
73   va_list args;
74   va_start(args, msg);
75   vfprintf(stderr, msg, args);
76   fputc('\n', stderr);
77   box_exit();
78 }
79
80 static void __attribute__((format(printf,1,2)))
81 msg(char *msg, ...)
82 {
83   va_list args;
84   va_start(args, msg);
85   if (verbose)
86     {
87       vfprintf(stderr, msg, args);
88       fflush(stderr);
89     }
90   va_end(args);
91 }
92
93 static const char * const syscall_tab[] = {
94 #include "syscall-table.h"
95 };
96 #define NUM_SYSCALLS (sizeof(syscall_tab)/sizeof(syscall_tab[0]))
97 #define NUM_ACTIONS (NUM_SYSCALLS+64)
98
99 enum syscall_action {
100   SC_DEFAULT,           // Use the default action
101   SC_NO,                // Always forbid
102   SC_YES,               // Always permit
103   SC_FILENAME,          // Permit if arg1 is a known filename
104   SC_LIBERAL = 128,     // Valid only in liberal mode
105 };
106
107 static unsigned char syscall_action[NUM_ACTIONS] = {
108 #define S(x) [__NR_##x]
109
110     // Syscalls permitted for specific file names
111     S(open) = SC_FILENAME,
112     S(creat) = SC_FILENAME,
113     S(unlink) = SC_FILENAME,
114     S(oldstat) = SC_FILENAME,
115     S(access) = SC_FILENAME,                    
116     S(oldlstat) = SC_FILENAME,                  
117     S(truncate) = SC_FILENAME,
118     S(stat) = SC_FILENAME,
119     S(lstat) = SC_FILENAME,
120     S(truncate64) = SC_FILENAME,
121     S(stat64) = SC_FILENAME,
122     S(lstat64) = SC_FILENAME,
123     S(readlink) = SC_FILENAME,
124
125     // Syscalls permitted always
126     S(exit) = SC_YES,
127     S(read) = SC_YES,
128     S(write) = SC_YES,
129     S(close) = SC_YES,
130     S(lseek) = SC_YES,
131     S(getpid) = SC_YES,
132     S(getuid) = SC_YES,
133     S(oldfstat) = SC_YES,
134     S(dup) = SC_YES,
135     S(brk) = SC_YES,
136     S(getgid) = SC_YES,
137     S(geteuid) = SC_YES,
138     S(getegid) = SC_YES,
139     S(dup2) = SC_YES,
140     S(ftruncate) = SC_YES,
141     S(fstat) = SC_YES,
142     S(personality) = SC_YES,
143     S(_llseek) = SC_YES,
144     S(readv) = SC_YES,
145     S(writev) = SC_YES,
146     S(getresuid) = SC_YES,
147 #ifdef __NR_pread64
148     S(pread64) = SC_YES,
149     S(pwrite64) = SC_YES,
150 #else
151     S(pread) = SC_YES,
152     S(pwrite) = SC_YES,
153 #endif
154     S(ftruncate64) = SC_YES,
155     S(fstat64) = SC_YES,
156     S(fcntl) = SC_YES,
157     S(fcntl64) = SC_YES,
158     S(mmap) = SC_YES,
159     S(munmap) = SC_YES,
160     S(ioctl) = SC_YES,
161     S(uname) = SC_YES,
162     S(gettid) = SC_YES,
163     S(set_thread_area) = SC_YES,
164     S(get_thread_area) = SC_YES,
165     S(exit_group) = SC_YES,
166
167     // Syscalls permitted only in liberal mode
168     S(time) = SC_YES | SC_LIBERAL,
169     S(alarm) = SC_YES | SC_LIBERAL,
170     S(pause) = SC_YES | SC_LIBERAL,
171     S(signal) = SC_YES | SC_LIBERAL,
172     S(fchmod) = SC_YES | SC_LIBERAL,
173     S(sigaction) = SC_YES | SC_LIBERAL,
174     S(sgetmask) = SC_YES | SC_LIBERAL,
175     S(ssetmask) = SC_YES | SC_LIBERAL,
176     S(sigsuspend) = SC_YES | SC_LIBERAL,
177     S(sigpending) = SC_YES | SC_LIBERAL,
178     S(getrlimit) = SC_YES | SC_LIBERAL,
179     S(getrusage) = SC_YES | SC_LIBERAL,
180     S(gettimeofday) = SC_YES | SC_LIBERAL,
181     S(select) = SC_YES | SC_LIBERAL,
182     S(readdir) = SC_YES | SC_LIBERAL,
183     S(setitimer) = SC_YES | SC_LIBERAL,
184     S(getitimer) = SC_YES | SC_LIBERAL,
185     S(sigreturn) = SC_YES | SC_LIBERAL,
186     S(mprotect) = SC_YES | SC_LIBERAL,
187     S(sigprocmask) = SC_YES | SC_LIBERAL,
188     S(getdents) = SC_YES | SC_LIBERAL,
189     S(getdents64) = SC_YES | SC_LIBERAL,
190     S(_newselect) = SC_YES | SC_LIBERAL,
191     S(fdatasync) = SC_YES | SC_LIBERAL,
192     S(mremap) = SC_YES | SC_LIBERAL,
193     S(poll) = SC_YES | SC_LIBERAL,
194     S(getcwd) = SC_YES | SC_LIBERAL,
195     S(nanosleep) = SC_YES | SC_LIBERAL,
196     S(rt_sigreturn) = SC_YES | SC_LIBERAL,
197     S(rt_sigaction) = SC_YES | SC_LIBERAL,
198     S(rt_sigprocmask) = SC_YES | SC_LIBERAL,
199     S(rt_sigpending) = SC_YES | SC_LIBERAL,
200     S(rt_sigtimedwait) = SC_YES | SC_LIBERAL,
201     S(rt_sigqueueinfo) = SC_YES | SC_LIBERAL,
202     S(rt_sigsuspend) = SC_YES | SC_LIBERAL,
203     S(mmap2) = SC_YES | SC_LIBERAL,
204     S(_sysctl) = SC_YES | SC_LIBERAL,
205 #undef S
206 };
207
208 static const char *
209 syscall_name(unsigned int id, char *buf)
210 {
211   if (id < NUM_SYSCALLS && syscall_tab[id])
212     return syscall_tab[id];
213   else
214     {
215       sprintf(buf, "#%d", id);
216       return buf;
217     }
218 }
219
220 static int
221 syscall_by_name(char *name)
222 {
223   for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
224     if (syscall_tab[i] && !strcmp(syscall_tab[i], name))
225       return i;
226   if (name[0] == '#')
227     name++;
228   if (!*name)
229     return -1;
230   char *ep;
231   unsigned long l = strtoul(name, &ep, 0);
232   if (*ep)
233     return -1;
234   if (l >= NUM_ACTIONS)
235     return NUM_ACTIONS;
236   return l;
237 }
238
239 static int
240 set_action(char *a)
241 {
242   char *sep = strchr(a, '=');
243   enum syscall_action act = SC_YES;
244   if (sep)
245     {
246       *sep++ = 0;
247       if (!strcmp(sep, "yes"))
248         act = SC_YES;
249       else if (!strcmp(sep, "no"))
250         act = SC_NO;
251       else if (!strcmp(sep, "file"))
252         act = SC_FILENAME;
253       else
254         return 0;
255     }
256
257   int sys = syscall_by_name(a);
258   if (sys < 0)
259     die("Unknown syscall `%s'", a);
260   if (sys >= (int)NUM_ACTIONS)
261     die("Syscall `%s' out of range", a);
262   syscall_action[sys] = act;
263   return 1;
264 }
265
266 static void
267 valid_filename(unsigned long addr)
268 {
269   char namebuf[4096], *p, *end;
270   static int mem_fd;
271
272   if (!file_access)
273     die("File access forbidden");
274   if (file_access >= 9)
275     return;
276
277   if (!mem_fd)
278     {
279       sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
280       mem_fd = open(namebuf, O_RDONLY);
281       if (mem_fd < 0)
282         die("open(%s): %m", namebuf);
283     }
284   p = end = namebuf;
285   do
286     {
287       if (p >= end)
288         {
289           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
290           int l = namebuf + sizeof(namebuf) - end;
291           if (l > remains)
292             l = remains;
293           if (!l)
294             die("Access to file with name too long");
295           if (long_seek(mem_fd, addr, SEEK_SET) < 0)
296             die("long_seek(mem): %m");
297           remains = read(mem_fd, end, l);
298           if (remains < 0)
299             die("read(mem): %m");
300           if (!remains)
301             die("Access to file with name out of memory");
302           end += l;
303           addr += l;
304         }
305     }
306   while (*p++);
307
308   msg("[%s] ", namebuf);
309   if (file_access >= 3)
310     return;
311   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
312     return;
313   if (file_access >= 2)
314     {
315       if ((!strncmp(namebuf, "/etc/", 5) ||
316            !strncmp(namebuf, "/lib/", 5) ||
317            !strncmp(namebuf, "/usr/lib/", 9) ||
318            !strncmp(namebuf, "/opt/lib/", 9))
319           && !strstr(namebuf, ".."))
320         return;
321       if (!strcmp(namebuf, "/dev/null") ||
322           !strcmp(namebuf, "/dev/zero") ||
323           !strcmp(namebuf, "/proc/meminfo") ||
324           !strcmp(namebuf, "/proc/self/stat") ||
325           !strcmp(namebuf, "/proc/self/exe") ||                 /* Needed by FPC 2.0.x runtime */
326           !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
327         return;
328     }
329   die("Forbidden access to file `%s'", namebuf);
330 }
331
332 static int
333 valid_syscall(struct user *u)
334 {
335   unsigned int sys = u->regs.orig_eax;
336   enum syscall_action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
337
338   if (act & SC_LIBERAL)
339     {
340       if (filter_syscalls == 1)
341         act &= ~SC_LIBERAL;
342       else
343         act = SC_DEFAULT;
344     }
345   switch (act)
346     {
347     case SC_YES:
348       return 1;
349     case SC_NO:
350       return 0;
351     case SC_FILENAME:
352       valid_filename(u->regs.ebx);
353       return 1;
354     default: ;
355     }
356
357   switch (sys)
358     {
359     case __NR_kill:
360       if (u->regs.ebx == box_pid)
361         die("Committed suicide by signal %d", (int)u->regs.ecx);
362       return 0;
363     case __NR_tgkill:
364       if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
365         die("Committed suicide by signal %d", (int)u->regs.edx);
366       return 0;
367     default:
368       return 0;
369     }
370 }
371
372 static void
373 signal_alarm(int unused UNUSED)
374 {
375   /* Time limit checks are synchronous, so we only schedule them there. */
376   timer_tick = 1;
377   alarm(1);
378 }
379
380 static void
381 signal_int(int unused UNUSED)
382 {
383   /* Interrupts are fatal, so no synchronization requirements. */
384   die("Interrupted");
385 }
386
387 static void
388 check_timeout(void)
389 {
390   if (wall_timeout)
391     {
392       struct timeval now, wall;
393       int wall_ms;
394       gettimeofday(&now, NULL);
395       timersub(&now, &start_time, &wall);
396       wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
397       if (wall_ms > wall_timeout)
398         die("Time limit exceeded (wall clock)");
399       if (verbose > 1)
400         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
401     }
402   if (timeout)
403     {
404       char buf[4096], *x;
405       int c, utime, stime, ms;
406       static int proc_status_fd;
407       if (!proc_status_fd)
408         {
409           sprintf(buf, "/proc/%d/stat", (int) box_pid);
410           proc_status_fd = open(buf, O_RDONLY);
411           if (proc_status_fd < 0)
412             die("open(%s): %m", buf);
413         }
414       lseek(proc_status_fd, 0, SEEK_SET);
415       if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
416         die("read on /proc/$pid/stat: %m");
417       if (c >= (int) sizeof(buf) - 1)
418         die("/proc/$pid/stat too long");
419       buf[c] = 0;
420       x = buf;
421       while (*x && *x != ' ')
422         x++;
423       while (*x == ' ')
424         x++;
425       if (*x++ != '(')
426         die("proc syntax error 1");
427       while (*x && (*x != ')' || x[1] != ' '))
428         x++;
429       while (*x == ')' || *x == ' ')
430         x++;
431       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
432         die("proc syntax error 2");
433       ms = (utime + stime) * 1000 / ticks_per_sec;
434       if (verbose > 1)
435         fprintf(stderr, "[time check: %d msec]\n", ms);
436       if (ms > timeout)
437         die("Time limit exceeded");
438     }
439 }
440
441 static void
442 boxkeeper(void)
443 {
444   int syscall_count = 0;
445   struct sigaction sa;
446
447   is_ptraced = 1;
448   bzero(&sa, sizeof(sa));
449   sa.sa_handler = signal_int;
450   sigaction(SIGINT, &sa, NULL);
451   gettimeofday(&start_time, NULL);
452   ticks_per_sec = sysconf(_SC_CLK_TCK);
453   if (ticks_per_sec <= 0)
454     die("Invalid ticks_per_sec!");
455   if (timeout || wall_timeout)
456     {
457       sa.sa_handler = signal_alarm;
458       sigaction(SIGALRM, &sa, NULL);
459       alarm(1);
460     }
461   for(;;)
462     {
463       struct rusage rus;
464       int stat;
465       pid_t p;
466       if (timer_tick)
467         {
468           check_timeout();
469           timer_tick = 0;
470         }
471       p = wait4(box_pid, &stat, WUNTRACED, &rus);
472       if (p < 0)
473         {
474           if (errno == EINTR)
475             continue;
476           die("wait4: %m");
477         }
478       if (p != box_pid)
479         die("wait4: unknown pid %d exited!", p);
480       if (WIFEXITED(stat))
481         {
482           struct timeval total, now, wall;
483           int total_ms, wall_ms;
484           box_pid = 0;
485           if (WEXITSTATUS(stat))
486             die("Exited with error status %d", WEXITSTATUS(stat));
487           timeradd(&rus.ru_utime, &rus.ru_stime, &total);
488           total_ms = total.tv_sec*1000 + total.tv_usec/1000;
489           gettimeofday(&now, NULL);
490           timersub(&now, &start_time, &wall);
491           wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
492           if (timeout && total_ms > timeout)
493             die("Time limit exceeded");
494           if (wall_timeout && wall_ms > wall_timeout)
495             die("Time limit exceeded (wall clock)");
496           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
497               (int) total.tv_sec, (int) total.tv_usec/1000,
498               (int) wall.tv_sec, (int) wall.tv_usec/1000,
499               syscall_count);
500           exit(0);
501         }
502       if (WIFSIGNALED(stat))
503         {
504           box_pid = 0;
505           die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
506         }
507       if (WIFSTOPPED(stat))
508         {
509           int sig = WSTOPSIG(stat);
510           if (sig == SIGTRAP)
511             {
512               struct user u;
513               static int stop_count = -1;
514               if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
515                 die("ptrace(PTRACE_GETREGS): %m");
516               stop_count++;
517               if (!stop_count)                  /* Traceme request */
518                 msg(">> Traceme request caught\n");
519               else if (stop_count & 1)          /* Syscall entry */
520                 {
521                   char namebuf[32];
522                   msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
523                   if (!exec_seen)
524                     {
525                       msg("[master] ");
526                       if (u.regs.orig_eax == __NR_execve)
527                         exec_seen = 1;
528                     }
529                   else if (valid_syscall(&u))
530                     syscall_count++;
531                   else
532                     {
533                       /*
534                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
535                        * so we have to change it to something harmless (e.g., an undefined
536                        * syscall) and make the program continue.
537                        */
538                       unsigned int sys = u.regs.orig_eax;
539                       u.regs.orig_eax = 0xffffffff;
540                       if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
541                         die("ptrace(PTRACE_SETREGS): %m");
542                       die("Forbidden syscall %s", syscall_name(sys, namebuf));
543                     }
544                 }
545               else                                      /* Syscall return */
546                 msg("= %ld\n", u.regs.eax);
547               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
548             }
549           else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
550             {
551               msg(">> Signal %d\n", sig);
552               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
553             }
554           else
555             die("Received signal %d", sig);
556         }
557       else
558         die("wait4: unknown status %x, giving up!", stat);
559     }
560 }
561
562 static void
563 box_inside(int argc, char **argv)
564 {
565   struct rlimit rl;
566   char *args[argc+1];
567   char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
568
569   memcpy(args, argv, argc * sizeof(char *));
570   args[argc] = NULL;
571   if (set_cwd && chdir(set_cwd))
572     die("chdir: %m");
573   if (redir_stdin)
574     {
575       close(0);
576       if (open(redir_stdin, O_RDONLY) != 0)
577         die("open(\"%s\"): %m", redir_stdin);
578     }
579   if (redir_stdout)
580     {
581       close(1);
582       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
583         die("open(\"%s\"): %m", redir_stdout);
584     }
585   dup2(1, 2);
586   setpgrp();
587   if (memory_limit)
588     {
589       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
590       if (setrlimit(RLIMIT_AS, &rl) < 0)
591         die("setrlimit: %m");
592     }
593   rl.rlim_cur = rl.rlim_max = 64;
594   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
595     die("setrlimit: %m");
596   if (filter_syscalls)
597     {
598       if (ptrace(PTRACE_TRACEME) < 0)
599         die("ptrace(PTRACE_TRACEME): %m");
600       /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
601       signal(SIGCHLD, SIG_IGN);
602       raise(SIGCHLD);
603     }
604   execve(args[0], args, (pass_environ ? environ : env));
605   die("execve(\"%s\"): %m", args[0]);
606 }
607
608 static void
609 usage(void)
610 {
611   fprintf(stderr, "Invalid arguments!\n");
612   printf("\
613 Usage: box [<options>] -- <command> <arguments>\n\
614 \n\
615 Options:\n\
616 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
617 -c <dir>\tChange directory to <dir> first\n\
618 -e\t\tPass full environment of parent process\n\
619 -f\t\tFilter system calls (-ff=very restricted)\n\
620 -i <file>\tRedirect stdin from <file>\n\
621 -m <size>\tLimit address space to <size> KB\n\
622 -o <file>\tRedirect stdout to <file>\n\
623 -s <sys>\tPermit the specified syscall (be careful)\n\
624 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
625 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
626 -T\t\tAllow syscalls for measuring run time\n\
627 -v\t\tBe verbose\n\
628 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
629 ");
630   exit(1);
631 }
632
633 int
634 main(int argc, char **argv)
635 {
636   int c;
637   uid_t uid;
638
639   while ((c = getopt(argc, argv, "a:c:efi:m:o:s:t:Tvw:")) >= 0)
640     switch (c)
641       {
642       case 'a':
643         file_access = atol(optarg);
644         break;
645       case 'c':
646         set_cwd = optarg;
647         break;
648       case 'e':
649         pass_environ = 1;
650         break;
651       case 'f':
652         filter_syscalls++;
653         break;
654       case 'i':
655         redir_stdin = optarg;
656         break;
657       case 'm':
658         memory_limit = atol(optarg);
659         break;
660       case 'o':
661         redir_stdout = optarg;
662         break;
663       case 's':
664         if (!set_action(optarg))
665           usage();
666         break;
667       case 't':
668         timeout = 1000*atof(optarg);
669         break;
670       case 'T':
671         syscall_action[__NR_times] = SC_YES;
672         break;
673       case 'v':
674         verbose++;
675         break;
676       case 'w':
677         wall_timeout = 1000*atof(optarg);
678         break;
679       default:
680         usage();
681       }
682   if (optind >= argc)
683     usage();
684
685   uid = geteuid();
686   if (setreuid(uid, uid) < 0)
687     die("setreuid: %m");
688   box_pid = fork();
689   if (box_pid < 0)
690     die("fork: %m");
691   if (!box_pid)
692     box_inside(argc-optind, argv+optind);
693   else
694     boxkeeper();
695   die("Internal error: fell over edge of the world");
696 }