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