]> mj.ucw.cz Git - eval.git/blob - src/box.c
Filtering of syscalls is now driven by a table.
[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 (!strcmp(syscall_tab[i], name))
225       return i;
226   return -1;
227 }
228
229 static void
230 valid_filename(unsigned long addr)
231 {
232   char namebuf[4096], *p, *end;
233   static int mem_fd;
234
235   if (!file_access)
236     die("File access forbidden");
237   if (file_access >= 9)
238     return;
239
240   if (!mem_fd)
241     {
242       sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
243       mem_fd = open(namebuf, O_RDONLY);
244       if (mem_fd < 0)
245         die("open(%s): %m", namebuf);
246     }
247   p = end = namebuf;
248   do
249     {
250       if (p >= end)
251         {
252           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
253           int l = namebuf + sizeof(namebuf) - end;
254           if (l > remains)
255             l = remains;
256           if (!l)
257             die("Access to file with name too long");
258           if (long_seek(mem_fd, addr, SEEK_SET) < 0)
259             die("long_seek(mem): %m");
260           remains = read(mem_fd, end, l);
261           if (remains < 0)
262             die("read(mem): %m");
263           if (!remains)
264             die("Access to file with name out of memory");
265           end += l;
266           addr += l;
267         }
268     }
269   while (*p++);
270
271   msg("[%s] ", namebuf);
272   if (file_access >= 3)
273     return;
274   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
275     return;
276   if (file_access >= 2)
277     {
278       if ((!strncmp(namebuf, "/etc/", 5) ||
279            !strncmp(namebuf, "/lib/", 5) ||
280            !strncmp(namebuf, "/usr/lib/", 9) ||
281            !strncmp(namebuf, "/opt/lib/", 9))
282           && !strstr(namebuf, ".."))
283         return;
284       if (!strcmp(namebuf, "/dev/null") ||
285           !strcmp(namebuf, "/dev/zero") ||
286           !strcmp(namebuf, "/proc/meminfo") ||
287           !strcmp(namebuf, "/proc/self/stat") ||
288           !strcmp(namebuf, "/proc/self/exe") ||                 /* Needed by FPC 2.0.x runtime */
289           !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
290         return;
291     }
292   die("Forbidden access to file `%s'", namebuf);
293 }
294
295 static int
296 valid_syscall(struct user *u)
297 {
298   unsigned int sys = u->regs.orig_eax;
299   enum syscall_action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
300
301   if (act & SC_LIBERAL)
302     {
303       if (filter_syscalls == 1)
304         act &= ~SC_LIBERAL;
305       else
306         act = SC_DEFAULT;
307     }
308   switch (act)
309     {
310     case SC_YES:
311       return 1;
312     case SC_NO:
313       return 0;
314     case SC_FILENAME:
315       valid_filename(u->regs.ebx);
316       return 1;
317     default: ;
318     }
319
320   switch (sys)
321     {
322     case __NR_kill:
323       if (u->regs.ebx == box_pid)
324         die("Committed suicide by signal %d", (int)u->regs.ecx);
325       return 0;
326     case __NR_tgkill:
327       if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
328         die("Committed suicide by signal %d", (int)u->regs.edx);
329       return 0;
330     default:
331       return 0;
332     }
333 }
334
335 static void
336 signal_alarm(int unused UNUSED)
337 {
338   /* Time limit checks are synchronous, so we only schedule them there. */
339   timer_tick = 1;
340   alarm(1);
341 }
342
343 static void
344 signal_int(int unused UNUSED)
345 {
346   /* Interrupts are fatal, so no synchronization requirements. */
347   die("Interrupted");
348 }
349
350 static void
351 check_timeout(void)
352 {
353   if (wall_timeout)
354     {
355       struct timeval now, wall;
356       int wall_ms;
357       gettimeofday(&now, NULL);
358       timersub(&now, &start_time, &wall);
359       wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
360       if (wall_ms > wall_timeout)
361         die("Time limit exceeded (wall clock)");
362       if (verbose > 1)
363         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
364     }
365   if (timeout)
366     {
367       char buf[4096], *x;
368       int c, utime, stime, ms;
369       static int proc_status_fd;
370       if (!proc_status_fd)
371         {
372           sprintf(buf, "/proc/%d/stat", (int) box_pid);
373           proc_status_fd = open(buf, O_RDONLY);
374           if (proc_status_fd < 0)
375             die("open(%s): %m", buf);
376         }
377       lseek(proc_status_fd, 0, SEEK_SET);
378       if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
379         die("read on /proc/$pid/stat: %m");
380       if (c >= (int) sizeof(buf) - 1)
381         die("/proc/$pid/stat too long");
382       buf[c] = 0;
383       x = buf;
384       while (*x && *x != ' ')
385         x++;
386       while (*x == ' ')
387         x++;
388       if (*x++ != '(')
389         die("proc syntax error 1");
390       while (*x && (*x != ')' || x[1] != ' '))
391         x++;
392       while (*x == ')' || *x == ' ')
393         x++;
394       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
395         die("proc syntax error 2");
396       ms = (utime + stime) * 1000 / ticks_per_sec;
397       if (verbose > 1)
398         fprintf(stderr, "[time check: %d msec]\n", ms);
399       if (ms > timeout)
400         die("Time limit exceeded");
401     }
402 }
403
404 static void
405 boxkeeper(void)
406 {
407   int syscall_count = 0;
408   struct sigaction sa;
409
410   is_ptraced = 1;
411   bzero(&sa, sizeof(sa));
412   sa.sa_handler = signal_int;
413   sigaction(SIGINT, &sa, NULL);
414   gettimeofday(&start_time, NULL);
415   ticks_per_sec = sysconf(_SC_CLK_TCK);
416   if (ticks_per_sec <= 0)
417     die("Invalid ticks_per_sec!");
418   if (timeout || wall_timeout)
419     {
420       sa.sa_handler = signal_alarm;
421       sigaction(SIGALRM, &sa, NULL);
422       alarm(1);
423     }
424   for(;;)
425     {
426       struct rusage rus;
427       int stat;
428       pid_t p;
429       if (timer_tick)
430         {
431           check_timeout();
432           timer_tick = 0;
433         }
434       p = wait4(box_pid, &stat, WUNTRACED, &rus);
435       if (p < 0)
436         {
437           if (errno == EINTR)
438             continue;
439           die("wait4: %m");
440         }
441       if (p != box_pid)
442         die("wait4: unknown pid %d exited!", p);
443       if (WIFEXITED(stat))
444         {
445           struct timeval total, now, wall;
446           int total_ms, wall_ms;
447           box_pid = 0;
448           if (WEXITSTATUS(stat))
449             die("Exited with error status %d", WEXITSTATUS(stat));
450           timeradd(&rus.ru_utime, &rus.ru_stime, &total);
451           total_ms = total.tv_sec*1000 + total.tv_usec/1000;
452           gettimeofday(&now, NULL);
453           timersub(&now, &start_time, &wall);
454           wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
455           if (timeout && total_ms > timeout)
456             die("Time limit exceeded");
457           if (wall_timeout && wall_ms > wall_timeout)
458             die("Time limit exceeded (wall clock)");
459           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
460               (int) total.tv_sec, (int) total.tv_usec/1000,
461               (int) wall.tv_sec, (int) wall.tv_usec/1000,
462               syscall_count);
463           exit(0);
464         }
465       if (WIFSIGNALED(stat))
466         {
467           box_pid = 0;
468           die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
469         }
470       if (WIFSTOPPED(stat))
471         {
472           int sig = WSTOPSIG(stat);
473           if (sig == SIGTRAP)
474             {
475               struct user u;
476               static int stop_count = -1;
477               if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
478                 die("ptrace(PTRACE_GETREGS): %m");
479               stop_count++;
480               if (!stop_count)                  /* Traceme request */
481                 msg(">> Traceme request caught\n");
482               else if (stop_count & 1)          /* Syscall entry */
483                 {
484                   char namebuf[32];
485                   msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
486                   if (!exec_seen)
487                     {
488                       msg("[master] ");
489                       if (u.regs.orig_eax == __NR_execve)
490                         exec_seen = 1;
491                     }
492                   else if (valid_syscall(&u))
493                     syscall_count++;
494                   else
495                     {
496                       /*
497                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
498                        * so we have to change it to something harmless (e.g., an undefined
499                        * syscall) and make the program continue.
500                        */
501                       unsigned int sys = u.regs.orig_eax;
502                       u.regs.orig_eax = 0xffffffff;
503                       if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
504                         die("ptrace(PTRACE_SETREGS): %m");
505                       die("Forbidden syscall %s", syscall_name(sys, namebuf));
506                     }
507                 }
508               else                                      /* Syscall return */
509                 msg("= %ld\n", u.regs.eax);
510               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
511             }
512           else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
513             {
514               msg(">> Signal %d\n", sig);
515               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
516             }
517           else
518             die("Received signal %d", sig);
519         }
520       else
521         die("wait4: unknown status %x, giving up!", stat);
522     }
523 }
524
525 static void
526 box_inside(int argc, char **argv)
527 {
528   struct rlimit rl;
529   char *args[argc+1];
530   char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
531
532   memcpy(args, argv, argc * sizeof(char *));
533   args[argc] = NULL;
534   if (set_cwd && chdir(set_cwd))
535     die("chdir: %m");
536   if (redir_stdin)
537     {
538       close(0);
539       if (open(redir_stdin, O_RDONLY) != 0)
540         die("open(\"%s\"): %m", redir_stdin);
541     }
542   if (redir_stdout)
543     {
544       close(1);
545       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
546         die("open(\"%s\"): %m", redir_stdout);
547     }
548   dup2(1, 2);
549   setpgrp();
550   if (memory_limit)
551     {
552       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
553       if (setrlimit(RLIMIT_AS, &rl) < 0)
554         die("setrlimit: %m");
555     }
556   rl.rlim_cur = rl.rlim_max = 64;
557   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
558     die("setrlimit: %m");
559   if (filter_syscalls)
560     {
561       if (ptrace(PTRACE_TRACEME) < 0)
562         die("ptrace(PTRACE_TRACEME): %m");
563       /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
564       signal(SIGCHLD, SIG_IGN);
565       raise(SIGCHLD);
566     }
567   execve(args[0], args, (pass_environ ? environ : env));
568   die("execve(\"%s\"): %m", args[0]);
569 }
570
571 static void
572 usage(void)
573 {
574   fprintf(stderr, "Invalid arguments!\n");
575   printf("\
576 Usage: box [<options>] -- <command> <arguments>\n\
577 \n\
578 Options:\n\
579 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
580 -c <dir>\tChange directory to <dir> first\n\
581 -e\t\tPass full environment of parent process\n\
582 -f\t\tFilter system calls (-ff=very restricted)\n\
583 -i <file>\tRedirect stdin from <file>\n\
584 -m <size>\tLimit address space to <size> KB\n\
585 -o <file>\tRedirect stdout to <file>\n\
586 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
587 -T\t\tAllow syscalls for measuring run time\n\
588 -v\t\tBe verbose\n\
589 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
590 ");
591   exit(1);
592 }
593
594 int
595 main(int argc, char **argv)
596 {
597   int c;
598   uid_t uid;
599
600   while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw:")) >= 0)
601     switch (c)
602       {
603       case 'a':
604         file_access = atol(optarg);
605         break;
606       case 'c':
607         set_cwd = optarg;
608         break;
609       case 'e':
610         pass_environ = 1;
611         break;
612       case 'f':
613         filter_syscalls++;
614         break;
615       case 'i':
616         redir_stdin = optarg;
617         break;
618       case 'm':
619         memory_limit = atol(optarg);
620         break;
621       case 'o':
622         redir_stdout = optarg;
623         break;
624       case 't':
625         timeout = 1000*atof(optarg);
626         break;
627       case 'T':
628         syscall_action[__NR_times] = SC_YES;
629         break;
630       case 'v':
631         verbose++;
632         break;
633       case 'w':
634         wall_timeout = 1000*atof(optarg);
635         break;
636       default:
637         usage();
638       }
639   if (optind >= argc)
640     usage();
641
642   uid = geteuid();
643   if (setreuid(uid, uid) < 0)
644     die("setreuid: %m");
645   box_pid = fork();
646   if (box_pid < 0)
647     die("fork: %m");
648   if (!box_pid)
649     box_inside(argc-optind, argv+optind);
650   else
651     boxkeeper();
652   die("Internal error: fell over edge of the world");
653 }