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