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