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