]> mj.ucw.cz Git - eval.git/blob - src/box.c
Default config for rhide.
[eval.git] / src / box.c
1 /*
2  *      A Simple Testing Sandbox
3  *
4  *      (c) 2001 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;
33 static int pass_environ;
34 static int use_wall_clock;
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
41 static pid_t box_pid;
42 static int is_ptraced;
43 static volatile int timer_tick;
44 static time_t start_time;
45 static int ticks_per_sec;
46
47 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
48 /* glibc 2.1 or newer -> has lseek64 */
49 #define long_seek(f,o,w) lseek64(f,o,w)
50 #else
51 /* Touching clandestine places in glibc */
52 extern loff_t llseek(int fd, loff_t pos, int whence);
53 #define long_seek(f,o,w) llseek(f,o,w)
54 #endif
55
56 static void NONRET
57 box_exit(void)
58 {
59   if (box_pid > 0)
60     {
61       if (is_ptraced)
62         ptrace(PTRACE_KILL, box_pid);
63       kill(-box_pid, SIGKILL);
64       kill(box_pid, SIGKILL);
65     }
66   exit(1);
67 }
68
69 static void NONRET __attribute__((format(printf,1,2)))
70 die(char *msg, ...)
71 {
72   va_list args;
73   va_start(args, msg);
74   vfprintf(stderr, msg, args);
75   fputc('\n', stderr);
76   box_exit();
77 }
78
79 static void __attribute__((format(printf,1,2)))
80 log(char *msg, ...)
81 {
82   va_list args;
83   va_start(args, msg);
84   if (verbose)
85     {
86       vfprintf(stderr, msg, args);
87       fflush(stderr);
88     }
89   va_end(args);
90 }
91
92 static void
93 valid_filename(unsigned long addr)
94 {
95   char namebuf[4096], *p, *end;
96   static int mem_fd;
97
98   if (!file_access)
99     die("File access forbidden.");
100   if (file_access >= 9)
101     return;
102
103   if (!mem_fd)
104     {
105       sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
106       mem_fd = open(namebuf, O_RDONLY);
107       if (mem_fd < 0)
108         die("open(%s): %m", namebuf);
109     }
110   p = end = namebuf;
111   do
112     {
113       if (p >= end)
114         {
115           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
116           int l = namebuf + sizeof(namebuf) - end;
117           if (l > remains)
118             l = remains;
119           if (!l)
120             die("Access to file with name too long.");
121           if (long_seek(mem_fd, addr, SEEK_SET) < 0)
122             die("long_seek(mem): %m");
123           remains = read(mem_fd, end, l);
124           if (remains < 0)
125             die("read(mem): %m");
126           if (!remains)
127             die("Access to file with name out of memory.");
128           end += l;
129           addr += l;
130         }
131     }
132   while (*p++);
133
134   log("[%s] ", namebuf);
135   if (file_access >= 3)
136     return;
137   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
138     return;
139   if (file_access >= 2)
140     {
141       if ((!strncmp(namebuf, "/etc/", 5) ||
142            !strncmp(namebuf, "/lib/", 5) ||
143            !strncmp(namebuf, "/usr/lib/", 9))
144           && !strstr(namebuf, ".."))
145         return;
146       if (!strcmp(namebuf, "/dev/null") ||
147           !strcmp(namebuf, "/dev/zero") ||
148           !strcmp(namebuf, "/proc/meminfo") ||
149           !strcmp(namebuf, "/proc/self/stat") ||
150           !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
151         return;
152     }
153   die("Forbidden access to file `%s'.", namebuf);
154 }
155
156 static int
157 valid_syscall(struct user *u)
158 {
159   switch (u->regs.orig_eax)
160     {
161     case SYS_execve:
162       {
163         static int exec_counter;
164         return !exec_counter++;
165       }
166     case SYS_open:
167     case SYS_creat:
168     case SYS_unlink:
169     case SYS_oldstat:
170     case SYS_access:                    
171     case SYS_oldlstat:                  
172     case SYS_truncate:
173     case SYS_stat:
174     case SYS_lstat:
175     case SYS_truncate64:
176     case SYS_stat64:
177     case SYS_lstat64:
178       valid_filename(u->regs.ebx);
179       return 1;
180     case SYS_exit:
181     case SYS_read:
182     case SYS_write:
183     case SYS_close:
184     case SYS_lseek:
185     case SYS_getpid:
186     case SYS_getuid:
187     case SYS_oldfstat:
188     case SYS_dup:
189     case SYS_brk:
190     case SYS_getgid:
191     case SYS_geteuid:
192     case SYS_getegid:
193     case SYS_dup2:
194     case SYS_ftruncate:
195     case SYS_fstat:
196     case SYS_personality:
197     case SYS__llseek:
198     case SYS_readv:
199     case SYS_writev:
200     case SYS_getresuid:
201     case SYS_pread:
202     case SYS_pwrite:
203     case SYS_ftruncate64:
204     case SYS_fstat64:
205     case SYS_fcntl:
206     case SYS_fcntl64:
207     case SYS_mmap:
208     case SYS_munmap:
209     case SYS_ioctl:
210     case SYS_uname:
211     case 252:
212       return 1;
213     case SYS_time:
214     case SYS_alarm:
215     case SYS_pause:
216     case SYS_signal:
217     case SYS_fchmod:
218     case SYS_sigaction:
219     case SYS_sgetmask:
220     case SYS_ssetmask:
221     case SYS_sigsuspend:
222     case SYS_sigpending:
223     case SYS_getrlimit:
224     case SYS_getrusage:
225     case SYS_gettimeofday:
226     case SYS_select:
227     case SYS_readdir:
228     case SYS_setitimer:
229     case SYS_getitimer:
230     case SYS_sigreturn:
231     case SYS_mprotect:
232     case SYS_sigprocmask:
233     case SYS_getdents:
234     case SYS_getdents64:
235     case SYS__newselect:
236     case SYS_fdatasync:
237     case SYS_mremap:
238     case SYS_poll:
239     case SYS_getcwd:
240     case SYS_nanosleep:
241     case SYS_rt_sigreturn:
242     case SYS_rt_sigaction:
243     case SYS_rt_sigprocmask:
244     case SYS_rt_sigpending:
245     case SYS_rt_sigtimedwait:
246     case SYS_rt_sigqueueinfo:
247     case SYS_rt_sigsuspend:
248     case SYS_mmap2:
249     case SYS__sysctl:
250       return (filter_syscalls == 1);
251     case SYS_times:
252       return allow_times;
253     default:
254       return 0;
255     }
256 }
257
258 static void
259 signal_alarm(int unused UNUSED)
260 {
261   /* Time limit checks are synchronous, so we only schedule them there. */
262   timer_tick = 1;
263   alarm(1);
264 }
265
266 static void
267 signal_int(int unused UNUSED)
268 {
269   /* Interrupts are fatal, so no synchronization requirements. */
270   die("Interrupted.");
271 }
272
273 static void
274 check_timeout(void)
275 {
276   int sec;
277
278   if (use_wall_clock)
279     sec = time(NULL) - start_time;
280   else
281     {
282       char buf[4096], *x;
283       int c, utime, stime;
284       static int proc_status_fd;
285       if (!proc_status_fd)
286         {
287           sprintf(buf, "/proc/%d/stat", (int) box_pid);
288           proc_status_fd = open(buf, O_RDONLY);
289           if (proc_status_fd < 0)
290             die("open(%s): %m", buf);
291         }
292       lseek(proc_status_fd, 0, SEEK_SET);
293       if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
294         die("read on /proc/$pid/stat: %m");
295       if (c >= (int) sizeof(buf) - 1)
296         die("/proc/$pid/stat too long");
297       buf[c] = 0;
298       x = buf;
299       while (*x && *x != ' ')
300         x++;
301       while (*x == ' ')
302         x++;
303       if (*x++ != '(')
304         die("proc syntax error 1");
305       while (*x && (*x != ')' || x[1] != ' '))
306         x++;
307       while (*x == ')' || *x == ' ')
308         x++;
309       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
310         die("proc syntax error 2");
311       sec = (utime + stime)/ticks_per_sec;
312     }
313   if (verbose > 1)
314     fprintf(stderr, "[timecheck: %d seconds]\n", sec);
315   if (sec > timeout)
316     die("Time limit exceeded.");
317 }
318
319 static void
320 boxkeeper(void)
321 {
322   int syscall_count = 0;
323   struct sigaction sa;
324
325   is_ptraced = 1;
326   bzero(&sa, sizeof(sa));
327   sa.sa_handler = signal_int;
328   sigaction(SIGINT, &sa, NULL);
329   start_time = time(NULL);
330   ticks_per_sec = sysconf(_SC_CLK_TCK);
331   if (ticks_per_sec <= 0)
332     die("Invalid ticks_per_sec!");
333   if (timeout)
334     {
335       sa.sa_handler = signal_alarm;
336       sigaction(SIGALRM, &sa, NULL);
337       alarm(1);
338     }
339   for(;;)
340     {
341       struct rusage rus;
342       int stat;
343       pid_t p;
344       if (timer_tick)
345         {
346           check_timeout();
347           timer_tick = 0;
348         }
349       p = wait4(box_pid, &stat, WUNTRACED, &rus);
350       if (p < 0)
351         {
352           if (errno == EINTR)
353             continue;
354           die("wait4: %m");
355         }
356       if (p != box_pid)
357         die("wait4: unknown pid %d exited!", p);
358       if (WIFEXITED(stat))
359         {
360           struct timeval total;
361           int wall;
362           box_pid = 0;
363           if (WEXITSTATUS(stat))
364             die("Exited with error status %d.", WEXITSTATUS(stat));
365           timeradd(&rus.ru_utime, &rus.ru_stime, &total);
366           wall = time(NULL) - start_time;
367           if ((use_wall_clock ? wall : total.tv_sec) > timeout)
368             die("Time limit exceeded (after exit).");
369           fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
370           exit(0);
371         }
372       if (WIFSIGNALED(stat))
373         {
374           box_pid = 0;
375           die("Caught fatal signal %d.", WTERMSIG(stat));
376         }
377       if (WIFSTOPPED(stat))
378         {
379           int sig = WSTOPSIG(stat);
380           if (sig == SIGTRAP)
381             {
382               struct user u;
383               static int stop_count = -1;
384               if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
385                 die("ptrace(PTRACE_GETREGS): %m");
386               stop_count++;
387               if (!stop_count)                  /* Traceme request */
388                 log(">> Traceme request caught\n");
389               else if (stop_count & 1)          /* Syscall entry */
390                 {
391                   log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
392                   syscall_count++;
393                   if (!valid_syscall(&u))
394                     {
395                       /*
396                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
397                        * so we have to change it to something harmless (e.g., an undefined
398                        * syscall) and make the program continue.
399                        */
400                       unsigned int sys = u.regs.orig_eax;
401                       u.regs.orig_eax = 0xffffffff;
402                       if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
403                         die("ptrace(PTRACE_SETREGS): %m");
404                       die("Forbidden syscall %d.", sys);
405                     }
406                 }
407               else                                      /* Syscall return */
408                 log("= %ld\n", u.regs.eax);
409               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
410             }
411           else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
412             {
413               log(">> Signal %d\n", sig);
414               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
415             }
416           else
417             die("Received signal %d.", sig);
418         }
419       else
420         die("wait4: unknown status %x, giving up!", stat);
421     }
422 }
423
424 static void
425 box_inside(int argc, char **argv)
426 {
427   struct rlimit rl;
428   char *args[argc+1];
429   char *env[1] = { NULL };
430
431   memcpy(args, argv, argc * sizeof(char *));
432   args[argc] = NULL;
433   if (redir_stdin)
434     {
435       close(0);
436       if (open(redir_stdin, O_RDONLY) != 0)
437         die("open(\"%s\"): %m", redir_stdin);
438     }
439   if (redir_stdout)
440     {
441       close(1);
442       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
443         die("open(\"%s\"): %m", redir_stdout);
444     }
445   close(2);
446   dup(1);
447   setpgrp();
448   if (memory_limit)
449     {
450       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
451       if (setrlimit(RLIMIT_AS, &rl) < 0)
452         die("setrlimit: %m");
453     }
454   rl.rlim_cur = rl.rlim_max = 64;
455   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
456     die("setrlimit: %m");
457   if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
458     die("ptrace(PTRACE_TRACEME): %m");
459   execve(args[0], args, (pass_environ ? environ : env));
460   die("execve(\"%s\"): %m", args[0]);
461 }
462
463 static void
464 usage(void)
465 {
466   fprintf(stderr, "Invalid arguments!\n");
467   printf("\
468 Usage: box [<options>] -- <command> <arguments>\n\
469 \n\
470 Options:\n\
471 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
472 -c <dir>\tChange directory to <dir> first\n\
473 -e\t\tPass full environment of parent process\n\
474 -f\t\tFilter system calls (-ff=very restricted)\n\
475 -i <file>\tRedirect stdin from <file>\n\
476 -m <size>\tLimit address space to <size> KB\n\
477 -o <file>\tRedirect stdout to <file>\n\
478 -t <time>\tStop after <time> seconds\n\
479 -T\t\tAllow syscalls for measuring run time\n\
480 -v\t\tBe verbose\n\
481 -w\t\tMeasure wall clock time instead of run time\n\
482 ");
483   exit(1);
484 }
485
486 int
487 main(int argc, char **argv)
488 {
489   int c;
490   uid_t uid;
491   char *cwd = NULL;
492
493   while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw")) >= 0)
494     switch (c)
495       {
496       case 'a':
497         file_access = atol(optarg);
498         break;
499       case 'c':
500         cwd = optarg;
501         break;
502       case 'e':
503         pass_environ = 1;
504         break;
505       case 'f':
506         filter_syscalls++;
507         break;
508       case 'i':
509         redir_stdin = optarg;
510         break;
511       case 'm':
512         memory_limit = atol(optarg);
513         break;
514       case 'o':
515         redir_stdout = optarg;
516         break;
517       case 't':
518         timeout = atol(optarg);
519         break;
520       case 'T':
521         allow_times++;
522         break;
523       case 'v':
524         verbose++;
525         break;
526       case 'w':
527         use_wall_clock = 1;
528         break;
529       default:
530         usage();
531       }
532   if (optind >= argc)
533     usage();
534
535   uid = geteuid();
536   if (setreuid(uid, uid) < 0)
537     die("setreuid: %m");
538   if (cwd && chdir(cwd))
539     die("chdir: %m");
540   box_pid = fork();
541   if (box_pid < 0)
542     die("fork: %m");
543   if (!box_pid)
544     box_inside(argc-optind, argv+optind);
545   else
546     boxkeeper();
547   die("Internal error: fell over edge of the world");
548 }