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