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