]> mj.ucw.cz Git - eval.git/blob - src/box.c
New names of syscalls.
[eval.git] / src / box.c
1 /*
2  *      A Simple Testing Sandbox
3  *
4  *      (c) 2001--2004 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 static char *set_cwd;
41
42 static pid_t box_pid;
43 static int is_ptraced;
44 static volatile int timer_tick;
45 static time_t start_time;
46 static int ticks_per_sec;
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 log(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 void
94 valid_filename(unsigned long addr)
95 {
96   char namebuf[4096], *p, *end;
97   static int mem_fd;
98
99   if (!file_access)
100     die("File access forbidden.");
101   if (file_access >= 9)
102     return;
103
104   if (!mem_fd)
105     {
106       sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
107       mem_fd = open(namebuf, O_RDONLY);
108       if (mem_fd < 0)
109         die("open(%s): %m", namebuf);
110     }
111   p = end = namebuf;
112   do
113     {
114       if (p >= end)
115         {
116           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
117           int l = namebuf + sizeof(namebuf) - end;
118           if (l > remains)
119             l = remains;
120           if (!l)
121             die("Access to file with name too long.");
122           if (long_seek(mem_fd, addr, SEEK_SET) < 0)
123             die("long_seek(mem): %m");
124           remains = read(mem_fd, end, l);
125           if (remains < 0)
126             die("read(mem): %m");
127           if (!remains)
128             die("Access to file with name out of memory.");
129           end += l;
130           addr += l;
131         }
132     }
133   while (*p++);
134
135   log("[%s] ", namebuf);
136   if (file_access >= 3)
137     return;
138   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
139     return;
140   if (file_access >= 2)
141     {
142       if ((!strncmp(namebuf, "/etc/", 5) ||
143            !strncmp(namebuf, "/lib/", 5) ||
144            !strncmp(namebuf, "/usr/lib/", 9))
145           && !strstr(namebuf, ".."))
146         return;
147       if (!strcmp(namebuf, "/dev/null") ||
148           !strcmp(namebuf, "/dev/zero") ||
149           !strcmp(namebuf, "/proc/meminfo") ||
150           !strcmp(namebuf, "/proc/self/stat") ||
151           !strncmp(namebuf, "/usr/share/zoneinfo/", 20))
152         return;
153     }
154   die("Forbidden access to file `%s'.", namebuf);
155 }
156
157 static int
158 valid_syscall(struct user *u)
159 {
160   switch (u->regs.orig_eax)
161     {
162     case __NR_execve:
163       {
164         static int exec_counter;
165         return !exec_counter++;
166       }
167     case __NR_open:
168     case __NR_creat:
169     case __NR_unlink:
170     case __NR_oldstat:
171     case __NR_access:                   
172     case __NR_oldlstat:                 
173     case __NR_truncate:
174     case __NR_stat:
175     case __NR_lstat:
176     case __NR_truncate64:
177     case __NR_stat64:
178     case __NR_lstat64:
179       valid_filename(u->regs.ebx);
180       return 1;
181     case __NR_exit:
182     case __NR_read:
183     case __NR_write:
184     case __NR_close:
185     case __NR_lseek:
186     case __NR_getpid:
187     case __NR_getuid:
188     case __NR_oldfstat:
189     case __NR_dup:
190     case __NR_brk:
191     case __NR_getgid:
192     case __NR_geteuid:
193     case __NR_getegid:
194     case __NR_dup2:
195     case __NR_ftruncate:
196     case __NR_fstat:
197     case __NR_personality:
198     case __NR__llseek:
199     case __NR_readv:
200     case __NR_writev:
201     case __NR_getresuid:
202 #ifdef __NR_pread64
203     case __NR_pread64:
204     case __NR_pwrite64:
205 #else
206     case __NR_pread:
207     case __NR_pwrite:
208 #endif
209     case __NR_ftruncate64:
210     case __NR_fstat64:
211     case __NR_fcntl:
212     case __NR_fcntl64:
213     case __NR_mmap:
214     case __NR_munmap:
215     case __NR_ioctl:
216     case __NR_uname:
217     case 252:
218       return 1;
219     case __NR_time:
220     case __NR_alarm:
221     case __NR_pause:
222     case __NR_signal:
223     case __NR_fchmod:
224     case __NR_sigaction:
225     case __NR_sgetmask:
226     case __NR_ssetmask:
227     case __NR_sigsuspend:
228     case __NR_sigpending:
229     case __NR_getrlimit:
230     case __NR_getrusage:
231     case __NR_gettimeofday:
232     case __NR_select:
233     case __NR_readdir:
234     case __NR_setitimer:
235     case __NR_getitimer:
236     case __NR_sigreturn:
237     case __NR_mprotect:
238     case __NR_sigprocmask:
239     case __NR_getdents:
240     case __NR_getdents64:
241     case __NR__newselect:
242     case __NR_fdatasync:
243     case __NR_mremap:
244     case __NR_poll:
245     case __NR_getcwd:
246     case __NR_nanosleep:
247     case __NR_rt_sigreturn:
248     case __NR_rt_sigaction:
249     case __NR_rt_sigprocmask:
250     case __NR_rt_sigpending:
251     case __NR_rt_sigtimedwait:
252     case __NR_rt_sigqueueinfo:
253     case __NR_rt_sigsuspend:
254     case __NR_mmap2:
255     case __NR__sysctl:
256       return (filter_syscalls == 1);
257     case __NR_times:
258       return allow_times;
259     case __NR_kill:
260       if (u->regs.ebx == box_pid)
261         die("Commited suicide by signal %d.", (int)u->regs.ecx);
262       return 0;
263     default:
264       return 0;
265     }
266 }
267
268 static void
269 signal_alarm(int unused UNUSED)
270 {
271   /* Time limit checks are synchronous, so we only schedule them there. */
272   timer_tick = 1;
273   alarm(1);
274 }
275
276 static void
277 signal_int(int unused UNUSED)
278 {
279   /* Interrupts are fatal, so no synchronization requirements. */
280   die("Interrupted.");
281 }
282
283 static void
284 check_timeout(void)
285 {
286   int sec;
287
288   if (use_wall_clock)
289     sec = time(NULL) - start_time;
290   else
291     {
292       char buf[4096], *x;
293       int c, utime, stime;
294       static int proc_status_fd;
295       if (!proc_status_fd)
296         {
297           sprintf(buf, "/proc/%d/stat", (int) box_pid);
298           proc_status_fd = open(buf, O_RDONLY);
299           if (proc_status_fd < 0)
300             die("open(%s): %m", buf);
301         }
302       lseek(proc_status_fd, 0, SEEK_SET);
303       if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
304         die("read on /proc/$pid/stat: %m");
305       if (c >= (int) sizeof(buf) - 1)
306         die("/proc/$pid/stat too long");
307       buf[c] = 0;
308       x = buf;
309       while (*x && *x != ' ')
310         x++;
311       while (*x == ' ')
312         x++;
313       if (*x++ != '(')
314         die("proc syntax error 1");
315       while (*x && (*x != ')' || x[1] != ' '))
316         x++;
317       while (*x == ')' || *x == ' ')
318         x++;
319       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
320         die("proc syntax error 2");
321       sec = (utime + stime)/ticks_per_sec;
322     }
323   if (verbose > 1)
324     fprintf(stderr, "[timecheck: %d seconds]\n", sec);
325   if (sec > timeout)
326     die("Time limit exceeded.");
327 }
328
329 static void
330 boxkeeper(void)
331 {
332   int syscall_count = 0;
333   struct sigaction sa;
334
335   is_ptraced = 1;
336   bzero(&sa, sizeof(sa));
337   sa.sa_handler = signal_int;
338   sigaction(SIGINT, &sa, NULL);
339   start_time = time(NULL);
340   ticks_per_sec = sysconf(_SC_CLK_TCK);
341   if (ticks_per_sec <= 0)
342     die("Invalid ticks_per_sec!");
343   if (timeout)
344     {
345       sa.sa_handler = signal_alarm;
346       sigaction(SIGALRM, &sa, NULL);
347       alarm(1);
348     }
349   for(;;)
350     {
351       struct rusage rus;
352       int stat;
353       pid_t p;
354       if (timer_tick)
355         {
356           check_timeout();
357           timer_tick = 0;
358         }
359       p = wait4(box_pid, &stat, WUNTRACED, &rus);
360       if (p < 0)
361         {
362           if (errno == EINTR)
363             continue;
364           die("wait4: %m");
365         }
366       if (p != box_pid)
367         die("wait4: unknown pid %d exited!", p);
368       if (WIFEXITED(stat))
369         {
370           struct timeval total;
371           int wall;
372           box_pid = 0;
373           if (WEXITSTATUS(stat))
374             die("Exited with error status %d.", WEXITSTATUS(stat));
375           timeradd(&rus.ru_utime, &rus.ru_stime, &total);
376           wall = time(NULL) - start_time;
377           if ((use_wall_clock ? wall : total.tv_sec) > timeout)
378             die("Time limit exceeded (after exit).");
379           fprintf(stderr, "OK (%d sec real, %d sec wall, %d syscalls)\n", (int) total.tv_sec, wall, syscall_count);
380           exit(0);
381         }
382       if (WIFSIGNALED(stat))
383         {
384           box_pid = 0;
385           die("Caught fatal signal %d.", WTERMSIG(stat));
386         }
387       if (WIFSTOPPED(stat))
388         {
389           int sig = WSTOPSIG(stat);
390           if (sig == SIGTRAP)
391             {
392               struct user u;
393               static int stop_count = -1;
394               if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
395                 die("ptrace(PTRACE_GETREGS): %m");
396               stop_count++;
397               if (!stop_count)                  /* Traceme request */
398                 log(">> Traceme request caught\n");
399               else if (stop_count & 1)          /* Syscall entry */
400                 {
401                   log(">> Syscall %3ld (%08lx,%08lx,%08lx) ", u.regs.orig_eax, u.regs.ebx, u.regs.ecx, u.regs.edx);
402                   syscall_count++;
403                   if (!valid_syscall(&u))
404                     {
405                       /*
406                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
407                        * so we have to change it to something harmless (e.g., an undefined
408                        * syscall) and make the program continue.
409                        */
410                       unsigned int sys = u.regs.orig_eax;
411                       u.regs.orig_eax = 0xffffffff;
412                       if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
413                         die("ptrace(PTRACE_SETREGS): %m");
414                       die("Forbidden syscall %d.", sys);
415                     }
416                 }
417               else                                      /* Syscall return */
418                 log("= %ld\n", u.regs.eax);
419               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
420             }
421           else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
422             {
423               log(">> Signal %d\n", sig);
424               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
425             }
426           else
427             die("Received signal %d.", sig);
428         }
429       else
430         die("wait4: unknown status %x, giving up!", stat);
431     }
432 }
433
434 static void
435 box_inside(int argc, char **argv)
436 {
437   struct rlimit rl;
438   char *args[argc+1];
439   char *env[1] = { NULL };
440
441   memcpy(args, argv, argc * sizeof(char *));
442   args[argc] = NULL;
443   if (set_cwd && chdir(set_cwd))
444     die("chdir: %m");
445   if (redir_stdin)
446     {
447       close(0);
448       if (open(redir_stdin, O_RDONLY) != 0)
449         die("open(\"%s\"): %m", redir_stdin);
450     }
451   if (redir_stdout)
452     {
453       close(1);
454       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
455         die("open(\"%s\"): %m", redir_stdout);
456     }
457   dup2(1, 2);
458   setpgrp();
459   if (memory_limit)
460     {
461       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
462       if (setrlimit(RLIMIT_AS, &rl) < 0)
463         die("setrlimit: %m");
464     }
465   rl.rlim_cur = rl.rlim_max = 64;
466   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
467     die("setrlimit: %m");
468   if (filter_syscalls && ptrace(PTRACE_TRACEME) < 0)
469     die("ptrace(PTRACE_TRACEME): %m");
470   execve(args[0], args, (pass_environ ? environ : env));
471   die("execve(\"%s\"): %m", args[0]);
472 }
473
474 static void
475 usage(void)
476 {
477   fprintf(stderr, "Invalid arguments!\n");
478   printf("\
479 Usage: box [<options>] -- <command> <arguments>\n\
480 \n\
481 Options:\n\
482 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
483 -c <dir>\tChange directory to <dir> first\n\
484 -e\t\tPass full environment of parent process\n\
485 -f\t\tFilter system calls (-ff=very restricted)\n\
486 -i <file>\tRedirect stdin from <file>\n\
487 -m <size>\tLimit address space to <size> KB\n\
488 -o <file>\tRedirect stdout to <file>\n\
489 -t <time>\tStop after <time> seconds\n\
490 -T\t\tAllow syscalls for measuring run time\n\
491 -v\t\tBe verbose\n\
492 -w\t\tMeasure wall clock time instead of run time\n\
493 ");
494   exit(1);
495 }
496
497 int
498 main(int argc, char **argv)
499 {
500   int c;
501   uid_t uid;
502
503   while ((c = getopt(argc, argv, "a:c:efi:m:o:t:Tvw")) >= 0)
504     switch (c)
505       {
506       case 'a':
507         file_access = atol(optarg);
508         break;
509       case 'c':
510         set_cwd = optarg;
511         break;
512       case 'e':
513         pass_environ = 1;
514         break;
515       case 'f':
516         filter_syscalls++;
517         break;
518       case 'i':
519         redir_stdin = optarg;
520         break;
521       case 'm':
522         memory_limit = atol(optarg);
523         break;
524       case 'o':
525         redir_stdout = optarg;
526         break;
527       case 't':
528         timeout = atol(optarg);
529         break;
530       case 'T':
531         allow_times++;
532         break;
533       case 'v':
534         verbose++;
535         break;
536       case 'w':
537         use_wall_clock = 1;
538         break;
539       default:
540         usage();
541       }
542   if (optind >= argc)
543     usage();
544
545   uid = geteuid();
546   if (setreuid(uid, uid) < 0)
547     die("setreuid: %m");
548   box_pid = fork();
549   if (box_pid < 0)
550     die("fork: %m");
551   if (!box_pid)
552     box_inside(argc-optind, argv+optind);
553   else
554     boxkeeper();
555   die("Internal error: fell over edge of the world");
556 }