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