]> mj.ucw.cz Git - eval.git/blobdiff - src/box.c
Filtering of syscalls is now driven by a table.
[eval.git] / src / box.c
index 095c8843ebdbe11d8b2342e45ab557339f1ab9d7..11ab37e854c2d2a496804061f00edacffd24dc76 100644 (file)
--- a/src/box.c
+++ b/src/box.c
@@ -1,7 +1,7 @@
 /*
- *     A Simple Testing Sandbox
+ *     A Simple Sandbox for MO-Eval
  *
- *     (c) 2001--2004 Martin Mares <mj@ucw.cz>
+ *     (c) 2001--2008 Martin Mares <mj@ucw.cz>
  */
 
 #define _LARGEFILE64_SOURCE
 #define UNUSED __attribute__((unused))
 
 static int filter_syscalls;            /* 0=off, 1=liberal, 2=totalitarian */
-static int timeout;
+static int timeout;                    /* milliseconds */
+static int wall_timeout;
 static int pass_environ;
-static int use_wall_clock;
 static int file_access;
 static int verbose;
 static int memory_limit;
-static int allow_times;
 static char *redir_stdin, *redir_stdout;
 static char *set_cwd;
 
 static pid_t box_pid;
 static int is_ptraced;
 static volatile int timer_tick;
-static time_t start_time;
+static struct timeval start_time;
 static int ticks_per_sec;
+static int exec_seen;
 
 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
 /* glibc 2.1 or newer -> has lseek64 */
@@ -78,7 +78,7 @@ die(char *msg, ...)
 }
 
 static void __attribute__((format(printf,1,2)))
-log(char *msg, ...)
+msg(char *msg, ...)
 {
   va_list args;
   va_start(args, msg);
@@ -90,6 +90,142 @@ log(char *msg, ...)
   va_end(args);
 }
 
+static const char * const syscall_tab[] = {
+#include "syscall-table.h"
+};
+#define NUM_SYSCALLS (sizeof(syscall_tab)/sizeof(syscall_tab[0]))
+#define NUM_ACTIONS (NUM_SYSCALLS+64)
+
+enum syscall_action {
+  SC_DEFAULT,          // Use the default action
+  SC_NO,               // Always forbid
+  SC_YES,              // Always permit
+  SC_FILENAME,         // Permit if arg1 is a known filename
+  SC_LIBERAL = 128,    // Valid only in liberal mode
+};
+
+static unsigned char syscall_action[NUM_ACTIONS] = {
+#define S(x) [__NR_##x]
+
+    // Syscalls permitted for specific file names
+    S(open) = SC_FILENAME,
+    S(creat) = SC_FILENAME,
+    S(unlink) = SC_FILENAME,
+    S(oldstat) = SC_FILENAME,
+    S(access) = SC_FILENAME,                   
+    S(oldlstat) = SC_FILENAME,                 
+    S(truncate) = SC_FILENAME,
+    S(stat) = SC_FILENAME,
+    S(lstat) = SC_FILENAME,
+    S(truncate64) = SC_FILENAME,
+    S(stat64) = SC_FILENAME,
+    S(lstat64) = SC_FILENAME,
+    S(readlink) = SC_FILENAME,
+
+    // Syscalls permitted always
+    S(exit) = SC_YES,
+    S(read) = SC_YES,
+    S(write) = SC_YES,
+    S(close) = SC_YES,
+    S(lseek) = SC_YES,
+    S(getpid) = SC_YES,
+    S(getuid) = SC_YES,
+    S(oldfstat) = SC_YES,
+    S(dup) = SC_YES,
+    S(brk) = SC_YES,
+    S(getgid) = SC_YES,
+    S(geteuid) = SC_YES,
+    S(getegid) = SC_YES,
+    S(dup2) = SC_YES,
+    S(ftruncate) = SC_YES,
+    S(fstat) = SC_YES,
+    S(personality) = SC_YES,
+    S(_llseek) = SC_YES,
+    S(readv) = SC_YES,
+    S(writev) = SC_YES,
+    S(getresuid) = SC_YES,
+#ifdef __NR_pread64
+    S(pread64) = SC_YES,
+    S(pwrite64) = SC_YES,
+#else
+    S(pread) = SC_YES,
+    S(pwrite) = SC_YES,
+#endif
+    S(ftruncate64) = SC_YES,
+    S(fstat64) = SC_YES,
+    S(fcntl) = SC_YES,
+    S(fcntl64) = SC_YES,
+    S(mmap) = SC_YES,
+    S(munmap) = SC_YES,
+    S(ioctl) = SC_YES,
+    S(uname) = SC_YES,
+    S(gettid) = SC_YES,
+    S(set_thread_area) = SC_YES,
+    S(get_thread_area) = SC_YES,
+    S(exit_group) = SC_YES,
+
+    // Syscalls permitted only in liberal mode
+    S(time) = SC_YES | SC_LIBERAL,
+    S(alarm) = SC_YES | SC_LIBERAL,
+    S(pause) = SC_YES | SC_LIBERAL,
+    S(signal) = SC_YES | SC_LIBERAL,
+    S(fchmod) = SC_YES | SC_LIBERAL,
+    S(sigaction) = SC_YES | SC_LIBERAL,
+    S(sgetmask) = SC_YES | SC_LIBERAL,
+    S(ssetmask) = SC_YES | SC_LIBERAL,
+    S(sigsuspend) = SC_YES | SC_LIBERAL,
+    S(sigpending) = SC_YES | SC_LIBERAL,
+    S(getrlimit) = SC_YES | SC_LIBERAL,
+    S(getrusage) = SC_YES | SC_LIBERAL,
+    S(gettimeofday) = SC_YES | SC_LIBERAL,
+    S(select) = SC_YES | SC_LIBERAL,
+    S(readdir) = SC_YES | SC_LIBERAL,
+    S(setitimer) = SC_YES | SC_LIBERAL,
+    S(getitimer) = SC_YES | SC_LIBERAL,
+    S(sigreturn) = SC_YES | SC_LIBERAL,
+    S(mprotect) = SC_YES | SC_LIBERAL,
+    S(sigprocmask) = SC_YES | SC_LIBERAL,
+    S(getdents) = SC_YES | SC_LIBERAL,
+    S(getdents64) = SC_YES | SC_LIBERAL,
+    S(_newselect) = SC_YES | SC_LIBERAL,
+    S(fdatasync) = SC_YES | SC_LIBERAL,
+    S(mremap) = SC_YES | SC_LIBERAL,
+    S(poll) = SC_YES | SC_LIBERAL,
+    S(getcwd) = SC_YES | SC_LIBERAL,
+    S(nanosleep) = SC_YES | SC_LIBERAL,
+    S(rt_sigreturn) = SC_YES | SC_LIBERAL,
+    S(rt_sigaction) = SC_YES | SC_LIBERAL,
+    S(rt_sigprocmask) = SC_YES | SC_LIBERAL,
+    S(rt_sigpending) = SC_YES | SC_LIBERAL,
+    S(rt_sigtimedwait) = SC_YES | SC_LIBERAL,
+    S(rt_sigqueueinfo) = SC_YES | SC_LIBERAL,
+    S(rt_sigsuspend) = SC_YES | SC_LIBERAL,
+    S(mmap2) = SC_YES | SC_LIBERAL,
+    S(_sysctl) = SC_YES | SC_LIBERAL,
+#undef S
+};
+
+static const char *
+syscall_name(unsigned int id, char *buf)
+{
+  if (id < NUM_SYSCALLS && syscall_tab[id])
+    return syscall_tab[id];
+  else
+    {
+      sprintf(buf, "#%d", id);
+      return buf;
+    }
+}
+
+static int
+syscall_by_name(char *name)
+{
+  for (unsigned int i=0; i<sizeof(syscall_tab)/sizeof(syscall_tab[0]); i++)
+    if (!strcmp(syscall_tab[i], name))
+      return i;
+  return -1;
+}
+
 static void
 valid_filename(unsigned long addr)
 {
@@ -97,7 +233,7 @@ valid_filename(unsigned long addr)
   static int mem_fd;
 
   if (!file_access)
-    die("File access forbidden.");
+    die("File access forbidden");
   if (file_access >= 9)
     return;
 
@@ -118,21 +254,21 @@ valid_filename(unsigned long addr)
          if (l > remains)
            l = remains;
          if (!l)
-           die("Access to file with name too long.");
+           die("Access to file with name too long");
          if (long_seek(mem_fd, addr, SEEK_SET) < 0)
            die("long_seek(mem): %m");
          remains = read(mem_fd, end, l);
          if (remains < 0)
            die("read(mem): %m");
          if (!remains)
-           die("Access to file with name out of memory.");
+           die("Access to file with name out of memory");
          end += l;
          addr += l;
        }
     }
   while (*p++);
 
-  log("[%s] ", namebuf);
+  msg("[%s] ", namebuf);
   if (file_access >= 3)
     return;
   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
@@ -153,122 +289,43 @@ valid_filename(unsigned long addr)
          !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
        return;
     }
-  die("Forbidden access to file `%s'.", namebuf);
+  die("Forbidden access to file `%s'", namebuf);
 }
 
 static int
 valid_syscall(struct user *u)
 {
-  switch (u->regs.orig_eax)
+  unsigned int sys = u->regs.orig_eax;
+  enum syscall_action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : SC_DEFAULT;
+
+  if (act & SC_LIBERAL)
     {
-    case __NR_execve:
-      {
-       static int exec_counter;
-       return !exec_counter++;
-      }
-    case __NR_open:
-    case __NR_creat:
-    case __NR_unlink:
-    case __NR_oldstat:
-    case __NR_access:                  
-    case __NR_oldlstat:                        
-    case __NR_truncate:
-    case __NR_stat:
-    case __NR_lstat:
-    case __NR_truncate64:
-    case __NR_stat64:
-    case __NR_lstat64:
-    case __NR_readlink:
-      valid_filename(u->regs.ebx);
+      if (filter_syscalls == 1)
+        act &= ~SC_LIBERAL;
+      else
+        act = SC_DEFAULT;
+    }
+  switch (act)
+    {
+    case SC_YES:
       return 1;
-    case __NR_exit:
-    case __NR_read:
-    case __NR_write:
-    case __NR_close:
-    case __NR_lseek:
-    case __NR_getpid:
-    case __NR_getuid:
-    case __NR_oldfstat:
-    case __NR_dup:
-    case __NR_brk:
-    case __NR_getgid:
-    case __NR_geteuid:
-    case __NR_getegid:
-    case __NR_dup2:
-    case __NR_ftruncate:
-    case __NR_fstat:
-    case __NR_personality:
-    case __NR__llseek:
-    case __NR_readv:
-    case __NR_writev:
-    case __NR_getresuid:
-#ifdef __NR_pread64
-    case __NR_pread64:
-    case __NR_pwrite64:
-#else
-    case __NR_pread:
-    case __NR_pwrite:
-#endif
-    case __NR_ftruncate64:
-    case __NR_fstat64:
-    case __NR_fcntl:
-    case __NR_fcntl64:
-    case __NR_mmap:
-    case __NR_munmap:
-    case __NR_ioctl:
-    case __NR_uname:
-    case __NR_gettid:
-    case __NR_set_thread_area:
-    case __NR_get_thread_area:
-    case __NR_exit_group:
+    case SC_NO:
+      return 0;
+    case SC_FILENAME:
+      valid_filename(u->regs.ebx);
       return 1;
-    case __NR_time:
-    case __NR_alarm:
-    case __NR_pause:
-    case __NR_signal:
-    case __NR_fchmod:
-    case __NR_sigaction:
-    case __NR_sgetmask:
-    case __NR_ssetmask:
-    case __NR_sigsuspend:
-    case __NR_sigpending:
-    case __NR_getrlimit:
-    case __NR_getrusage:
-    case __NR_gettimeofday:
-    case __NR_select:
-    case __NR_readdir:
-    case __NR_setitimer:
-    case __NR_getitimer:
-    case __NR_sigreturn:
-    case __NR_mprotect:
-    case __NR_sigprocmask:
-    case __NR_getdents:
-    case __NR_getdents64:
-    case __NR__newselect:
-    case __NR_fdatasync:
-    case __NR_mremap:
-    case __NR_poll:
-    case __NR_getcwd:
-    case __NR_nanosleep:
-    case __NR_rt_sigreturn:
-    case __NR_rt_sigaction:
-    case __NR_rt_sigprocmask:
-    case __NR_rt_sigpending:
-    case __NR_rt_sigtimedwait:
-    case __NR_rt_sigqueueinfo:
-    case __NR_rt_sigsuspend:
-    case __NR_mmap2:
-    case __NR__sysctl:
-      return (filter_syscalls == 1);
-    case __NR_times:
-      return allow_times;
+    default: ;
+    }
+
+  switch (sys)
+    {
     case __NR_kill:
       if (u->regs.ebx == box_pid)
-       die("Commited suicide by signal %d.", (int)u->regs.ecx);
+       die("Committed suicide by signal %d", (int)u->regs.ecx);
       return 0;
     case __NR_tgkill:
       if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
-       die("Commited suicide by signal %d.", (int)u->regs.edx);
+       die("Committed suicide by signal %d", (int)u->regs.edx);
       return 0;
     default:
       return 0;
@@ -287,20 +344,28 @@ static void
 signal_int(int unused UNUSED)
 {
   /* Interrupts are fatal, so no synchronization requirements. */
-  die("Interrupted.");
+  die("Interrupted");
 }
 
 static void
 check_timeout(void)
 {
-  int sec;
-
-  if (use_wall_clock)
-    sec = time(NULL) - start_time;
-  else
+  if (wall_timeout)
+    {
+      struct timeval now, wall;
+      int wall_ms;
+      gettimeofday(&now, NULL);
+      timersub(&now, &start_time, &wall);
+      wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
+      if (wall_ms > wall_timeout)
+        die("Time limit exceeded (wall clock)");
+      if (verbose > 1)
+        fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
+    }
+  if (timeout)
     {
       char buf[4096], *x;
-      int c, utime, stime;
+      int c, utime, stime, ms;
       static int proc_status_fd;
       if (!proc_status_fd)
        {
@@ -328,12 +393,12 @@ check_timeout(void)
        x++;
       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
        die("proc syntax error 2");
-      sec = (utime + stime)/ticks_per_sec;
+      ms = (utime + stime) * 1000 / ticks_per_sec;
+      if (verbose > 1)
+       fprintf(stderr, "[time check: %d msec]\n", ms);
+      if (ms > timeout)
+       die("Time limit exceeded");
     }
-  if (verbose > 1)
-    fprintf(stderr, "[timecheck: %d seconds]\n", sec);
-  if (sec > timeout)
-    die("Time limit exceeded.");
 }
 
 static void
@@ -346,11 +411,11 @@ boxkeeper(void)
   bzero(&sa, sizeof(sa));
   sa.sa_handler = signal_int;
   sigaction(SIGINT, &sa, NULL);
-  start_time = time(NULL);
+  gettimeofday(&start_time, NULL);
   ticks_per_sec = sysconf(_SC_CLK_TCK);
   if (ticks_per_sec <= 0)
     die("Invalid ticks_per_sec!");
-  if (timeout)
+  if (timeout || wall_timeout)
     {
       sa.sa_handler = signal_alarm;
       sigaction(SIGALRM, &sa, NULL);
@@ -377,22 +442,30 @@ boxkeeper(void)
        die("wait4: unknown pid %d exited!", p);
       if (WIFEXITED(stat))
        {
-         struct timeval total;
-         int wall;
+         struct timeval total, now, wall;
+         int total_ms, wall_ms;
          box_pid = 0;
          if (WEXITSTATUS(stat))
-           die("Exited with error status %d.", WEXITSTATUS(stat));
+           die("Exited with error status %d", WEXITSTATUS(stat));
          timeradd(&rus.ru_utime, &rus.ru_stime, &total);
-         wall = time(NULL) - start_time;
-         if ((use_wall_clock ? wall : total.tv_sec) > timeout)
-           die("Time limit exceeded (after exit).");
-         fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
+         total_ms = total.tv_sec*1000 + total.tv_usec/1000;
+         gettimeofday(&now, NULL);
+         timersub(&now, &start_time, &wall);
+         wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
+         if (timeout && total_ms > timeout)
+           die("Time limit exceeded");
+         if (wall_timeout && wall_ms > wall_timeout)
+           die("Time limit exceeded (wall clock)");
+         fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
+             (int) total.tv_sec, (int) total.tv_usec/1000,
+             (int) wall.tv_sec, (int) wall.tv_usec/1000,
+             syscall_count);
          exit(0);
        }
       if (WIFSIGNALED(stat))
        {
          box_pid = 0;
-         die("Caught fatal signal %d.", WTERMSIG(stat));
+         die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
        }
       if (WIFSTOPPED(stat))
        {
@@ -405,12 +478,20 @@ boxkeeper(void)
                die("ptrace(PTRACE_GETREGS): %m");
              stop_count++;
              if (!stop_count)                  /* Traceme request */
-               log(">> Traceme request caught\n");
+               msg(">> Traceme request caught\n");
              else if (stop_count & 1)          /* Syscall entry */
                {
-                 log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
-                 syscall_count++;
-                 if (!valid_syscall(&u))
+                 char namebuf[32];
+                 msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
+                 if (!exec_seen)
+                   {
+                     msg("[master] ");
+                     if (u.regs.orig_eax == __NR_execve)
+                       exec_seen = 1;
+                   }
+                 else if (valid_syscall(&u))
+                   syscall_count++;
+                 else
                    {
                      /*
                       * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
@@ -421,20 +502,20 @@ boxkeeper(void)
                      u.regs.orig_eax = 0xffffffff;
                      if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
                        die("ptrace(PTRACE_SETREGS): %m");
-                     die("Forbidden syscall %d.", sys);
+                     die("Forbidden syscall %s", syscall_name(sys, namebuf));
                    }
                }
              else                                      /* Syscall return */
-               log("= %ld\n", u.regs.eax);
+               msg("= %ld\n", u.regs.eax);
              ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
            }
          else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
            {
-             log(">> Signal %d\n", sig);
+             msg(">> Signal %d\n", sig);
              ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
            }
          else
-           die("Received signal %d.", sig);
+           die("Received signal %d", sig);
        }
       else
        die("wait4: unknown status %x, giving up!", stat);
@@ -446,7 +527,7 @@ box_inside(int argc, char **argv)
 {
   struct rlimit rl;
   char *args[argc+1];
-  char *env[1] = { NULL };
+  char *env[] = { "LIBC_FATAL_STDERR_=1", NULL };
 
   memcpy(args, argv, argc * sizeof(char *));
   args[argc] = NULL;
@@ -475,8 +556,14 @@ box_inside(int argc, char **argv)
   rl.rlim_cur = rl.rlim_max = 64;
   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
     die("setrlimit: %m");
-  if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
-    die("ptrace(PTRACE_TRACEME): %m");
+  if (filter_syscalls)
+    {
+      if (ptrace(PTRACE_TRACEME) < 0)
+       die("ptrace(PTRACE_TRACEME): %m");
+      /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
+      signal(SIGCHLD, SIG_IGN);
+      raise(SIGCHLD);
+    }
   execve(args[0], args, (pass_environ ? environ : env));
   die("execve(\"%s\"): %m", args[0]);
 }
@@ -496,10 +583,10 @@ Options:\n\
 -i <file>\tRedirect stdin from <file>\n\
 -m <size>\tLimit address space to <size> KB\n\
 -o <file>\tRedirect stdout to <file>\n\
--t <time>\tStop after <time> seconds\n\
+-t <time>\tSet run time limit (seconds, fractions allowed)\n\
 -T\t\tAllow syscalls for measuring run time\n\
 -v\t\tBe verbose\n\
--w\t\tMeasure wall clock time instead of run time\n\
+-w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
 ");
   exit(1);
 }
@@ -510,7 +597,7 @@ main(int argc, char **argv)
   int c;
   uid_t uid;
 
-  while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw")) >= 0)
+  while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw:")) >= 0)
     switch (c)
       {
       case 'a':
@@ -535,16 +622,16 @@ main(int argc, char **argv)
        redir_stdout = optarg;
        break;
       case 't':
-       timeout = atol(optarg);
+       timeout = 1000*atof(optarg);
        break;
       case 'T':
-       allow_times++;
+       syscall_action[__NR_times] = SC_YES;
        break;
       case 'v':
        verbose++;
        break;
       case 'w':
-       use_wall_clock = 1;
+        wall_timeout = 1000*atof(optarg);
        break;
       default:
        usage();