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