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