]> mj.ucw.cz Git - moe.git/blob - box/box.c
Changed formatting of time metas.
[moe.git] / box / box.c
1 /*
2  *      A Simple Sandbox for MO-Eval
3  *
4  *      (c) 2001--2008 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 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
31
32 static int filter_syscalls;             /* 0=off, 1=liberal, 2=totalitarian */
33 static int timeout;                     /* milliseconds */
34 static int wall_timeout;
35 static int pass_environ;
36 static int file_access;
37 static int verbose;
38 static int memory_limit;
39 static char *redir_stdin, *redir_stdout, *redir_stderr;
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 struct timeval start_time;
46 static int ticks_per_sec;
47 static int exec_seen;
48 static int partial_line;
49
50 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ > 0
51 /* glibc 2.1 or newer -> has lseek64 */
52 #define long_seek(f,o,w) lseek64(f,o,w)
53 #else
54 /* Touching clandestine places in glibc */
55 extern loff_t llseek(int fd, loff_t pos, int whence);
56 #define long_seek(f,o,w) llseek(f,o,w)
57 #endif
58
59 static void die(char *msg, ...) NONRET;
60
61 /*** Meta-files ***/
62
63 static FILE *metafile;
64
65 static void
66 meta_open(const char *name)
67 {
68   if (!strcmp(name, "-"))
69     {
70       metafile = stdout;
71       return;
72     }
73   metafile = fopen(name, "w");
74   if (!metafile)
75     die("Failed to open metafile '%s'",name);
76 }
77
78 static void
79 meta_close(void)
80 {
81   if (metafile && metafile != stdout)
82     fclose(metafile);
83 }
84
85 static void __attribute__((format(printf,1,2)))
86 meta_printf(const char *fmt, ...)
87 {
88   if (!metafile)
89     return;
90
91   va_list args;
92   va_start(args, fmt);
93   vfprintf(metafile, fmt, args);
94   va_end(args);
95 }
96
97 static int total_ms, wall_ms;
98
99 static void
100 final_stats(struct rusage *rus)
101 {
102   struct timeval total, now, wall;
103   timeradd(&rus->ru_utime, &rus->ru_stime, &total);
104   total_ms = total.tv_sec*1000 + total.tv_usec/1000;
105   gettimeofday(&now, NULL);
106   // FIXME: We are not guaranteed to have start_time always initialized
107   timersub(&now, &start_time, &wall);
108   wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
109
110   meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
111   meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
112 }
113
114 /*** Messages and exits ***/
115
116 static void NONRET
117 box_exit(int rc)
118 {
119   if (box_pid > 0)
120     {
121       if (is_ptraced)
122         ptrace(PTRACE_KILL, box_pid);
123       kill(-box_pid, SIGKILL);
124       kill(box_pid, SIGKILL);
125
126       struct rusage rus;
127       int stat;
128       int p = wait4(box_pid, &stat, 0, &rus);
129       if (p < 0)
130         fprintf(stderr, "UGH: Lost track of the process\n");
131       else
132         final_stats(&rus);
133     }
134   meta_close();
135   exit(rc);
136 }
137
138 static void
139 flush_line(void)
140 {
141   if (partial_line)
142     fputc('\n', stderr);
143   partial_line = 0;
144 }
145
146 static void NONRET __attribute__((format(printf,1,2)))
147 die(char *msg, ...)
148 {
149   va_list args;
150   va_start(args, msg);
151   flush_line();
152   vfprintf(stderr, msg, args);
153   fputc('\n', stderr);
154   box_exit(1);
155   // FIXME: exit(2) for errors of the box itself
156 }
157
158 static void __attribute__((format(printf,1,2)))
159 msg(char *msg, ...)
160 {
161   va_list args;
162   va_start(args, msg);
163   if (verbose)
164     {
165       int len = strlen(msg);
166       if (len > 0)
167         partial_line = (msg[len-1] != '\n');
168       vfprintf(stderr, msg, args);
169       fflush(stderr);
170     }
171   va_end(args);
172 }
173
174 static void *
175 xmalloc(size_t size)
176 {
177   void *p = malloc(size);
178   if (!p)
179     die("Out of memory");
180   return p;
181 }
182
183 /*** Syscall rules ***/
184
185 static const char * const syscall_names[] = {
186 #include "box/syscall-table.h"
187 };
188 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
189 #define NUM_ACTIONS (NUM_SYSCALLS+64)
190
191 enum action {
192   A_DEFAULT,            // Use the default action
193   A_NO,                 // Always forbid
194   A_YES,                // Always permit
195   A_FILENAME,           // Permit if arg1 is a known filename
196   A_LIBERAL = 128,      // Valid only in liberal mode
197 };
198
199 static unsigned char syscall_action[NUM_ACTIONS] = {
200 #define S(x) [__NR_##x]
201
202     // Syscalls permitted for specific file names
203     S(open) = A_FILENAME,
204     S(creat) = A_FILENAME,
205     S(unlink) = A_FILENAME,
206     S(oldstat) = A_FILENAME,
207     S(access) = A_FILENAME,                     
208     S(oldlstat) = A_FILENAME,                   
209     S(truncate) = A_FILENAME,
210     S(stat) = A_FILENAME,
211     S(lstat) = A_FILENAME,
212     S(truncate64) = A_FILENAME,
213     S(stat64) = A_FILENAME,
214     S(lstat64) = A_FILENAME,
215     S(readlink) = A_FILENAME,
216
217     // Syscalls permitted always
218     S(exit) = A_YES,
219     S(read) = A_YES,
220     S(write) = A_YES,
221     S(close) = A_YES,
222     S(lseek) = A_YES,
223     S(getpid) = A_YES,
224     S(getuid) = A_YES,
225     S(oldfstat) = A_YES,
226     S(dup) = A_YES,
227     S(brk) = A_YES,
228     S(getgid) = A_YES,
229     S(geteuid) = A_YES,
230     S(getegid) = A_YES,
231     S(dup2) = A_YES,
232     S(ftruncate) = A_YES,
233     S(fstat) = A_YES,
234     S(personality) = A_YES,
235     S(_llseek) = A_YES,
236     S(readv) = A_YES,
237     S(writev) = A_YES,
238     S(getresuid) = A_YES,
239 #ifdef __NR_pread64
240     S(pread64) = A_YES,
241     S(pwrite64) = A_YES,
242 #else
243     S(pread) = A_YES,
244     S(pwrite) = A_YES,
245 #endif
246     S(ftruncate64) = A_YES,
247     S(fstat64) = A_YES,
248     S(fcntl) = A_YES,
249     S(fcntl64) = A_YES,
250     S(mmap) = A_YES,
251     S(munmap) = A_YES,
252     S(ioctl) = A_YES,
253     S(uname) = A_YES,
254     S(gettid) = A_YES,
255     S(set_thread_area) = A_YES,
256     S(get_thread_area) = A_YES,
257     S(exit_group) = A_YES,
258
259     // Syscalls permitted only in liberal mode
260     S(time) = A_YES | A_LIBERAL,
261     S(alarm) = A_YES | A_LIBERAL,
262     S(pause) = A_YES | A_LIBERAL,
263     S(signal) = A_YES | A_LIBERAL,
264     S(fchmod) = A_YES | A_LIBERAL,
265     S(sigaction) = A_YES | A_LIBERAL,
266     S(sgetmask) = A_YES | A_LIBERAL,
267     S(ssetmask) = A_YES | A_LIBERAL,
268     S(sigsuspend) = A_YES | A_LIBERAL,
269     S(sigpending) = A_YES | A_LIBERAL,
270     S(getrlimit) = A_YES | A_LIBERAL,
271     S(getrusage) = A_YES | A_LIBERAL,
272     S(ugetrlimit) = A_YES | A_LIBERAL,
273     S(gettimeofday) = A_YES | A_LIBERAL,
274     S(select) = A_YES | A_LIBERAL,
275     S(readdir) = A_YES | A_LIBERAL,
276     S(setitimer) = A_YES | A_LIBERAL,
277     S(getitimer) = A_YES | A_LIBERAL,
278     S(sigreturn) = A_YES | A_LIBERAL,
279     S(mprotect) = A_YES | A_LIBERAL,
280     S(sigprocmask) = A_YES | A_LIBERAL,
281     S(getdents) = A_YES | A_LIBERAL,
282     S(getdents64) = A_YES | A_LIBERAL,
283     S(_newselect) = A_YES | A_LIBERAL,
284     S(fdatasync) = A_YES | A_LIBERAL,
285     S(mremap) = A_YES | A_LIBERAL,
286     S(poll) = A_YES | A_LIBERAL,
287     S(getcwd) = A_YES | A_LIBERAL,
288     S(nanosleep) = A_YES | A_LIBERAL,
289     S(rt_sigreturn) = A_YES | A_LIBERAL,
290     S(rt_sigaction) = A_YES | A_LIBERAL,
291     S(rt_sigprocmask) = A_YES | A_LIBERAL,
292     S(rt_sigpending) = A_YES | A_LIBERAL,
293     S(rt_sigtimedwait) = A_YES | A_LIBERAL,
294     S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
295     S(rt_sigsuspend) = A_YES | A_LIBERAL,
296     S(mmap2) = A_YES | A_LIBERAL,
297     S(_sysctl) = A_YES | A_LIBERAL,
298 #undef S
299 };
300
301 static const char *
302 syscall_name(unsigned int id, char *buf)
303 {
304   if (id < NUM_SYSCALLS && syscall_names[id])
305     return syscall_names[id];
306   else
307     {
308       sprintf(buf, "#%d", id);
309       return buf;
310     }
311 }
312
313 static int
314 syscall_by_name(char *name)
315 {
316   for (unsigned int i=0; i<NUM_SYSCALLS; i++)
317     if (syscall_names[i] && !strcmp(syscall_names[i], name))
318       return i;
319   if (name[0] == '#')
320     name++;
321   if (!*name)
322     return -1;
323   char *ep;
324   unsigned long l = strtoul(name, &ep, 0);
325   if (*ep)
326     return -1;
327   if (l >= NUM_ACTIONS)
328     return NUM_ACTIONS;
329   return l;
330 }
331
332 static int
333 set_syscall_action(char *a)
334 {
335   char *sep = strchr(a, '=');
336   enum action act = A_YES;
337   if (sep)
338     {
339       *sep++ = 0;
340       if (!strcmp(sep, "yes"))
341         act = A_YES;
342       else if (!strcmp(sep, "no"))
343         act = A_NO;
344       else if (!strcmp(sep, "file"))
345         act = A_FILENAME;
346       else
347         return 0;
348     }
349
350   int sys = syscall_by_name(a);
351   if (sys < 0)
352     die("Unknown syscall `%s'", a);
353   if (sys >= NUM_ACTIONS)
354     die("Syscall `%s' out of range", a);
355   syscall_action[sys] = act;
356   return 1;
357 }
358
359 /*** Path rules ***/
360
361 struct path_rule {
362   char *path;
363   enum action action;
364   struct path_rule *next;
365 };
366
367 static struct path_rule default_path_rules[] = {
368   { "/etc/", A_YES },
369   { "/lib/", A_YES },
370   { "/usr/lib/", A_YES },
371   { "/opt/lib/", A_YES },
372   { "/usr/share/zoneinfo/", A_YES },
373   { "/usr/share/locale/", A_YES },
374   { "/dev/null", A_YES },
375   { "/dev/zero", A_YES },
376   { "/proc/meminfo", A_YES },
377   { "/proc/self/stat", A_YES },
378   { "/proc/self/exe", A_YES },                  // Needed by FPC 2.0.x runtime
379 };
380
381 static struct path_rule *user_path_rules;
382 static struct path_rule **last_path_rule = &user_path_rules;
383
384 static int
385 set_path_action(char *a)
386 {
387   char *sep = strchr(a, '=');
388   enum action act = A_YES;
389   if (sep)
390     {
391       *sep++ = 0;
392       if (!strcmp(sep, "yes"))
393         act = A_YES;
394       else if (!strcmp(sep, "no"))
395         act = A_NO;
396       else
397         return 0;
398     }
399
400   struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
401   r->path = (char *)(r+1);
402   strcpy(r->path, a);
403   r->action = act;
404   r->next = NULL;
405   *last_path_rule = r;
406   last_path_rule = &r->next;
407   return 1;
408 }
409
410 static enum action
411 match_path_rule(struct path_rule *r, char *path)
412 {
413   char *rr = r->path;
414   while (*rr)
415     if (*rr++ != *path++)
416       {
417         if (rr[-1] == '/' && !path[-1])
418           break;
419         return A_DEFAULT;
420       }
421   if (rr > r->path && rr[-1] != '/' && *path)
422     return A_DEFAULT;
423   return r->action;
424 }
425
426 /*** Environment rules ***/
427
428 struct env_rule {
429   char *var;                    // Variable to match
430   char *val;                    // ""=clear, NULL=inherit
431   int var_len;
432   struct env_rule *next;
433 };
434
435 static struct env_rule *first_env_rule;
436 static struct env_rule **last_env_rule = &first_env_rule;
437
438 static struct env_rule default_env_rules[] = {
439   { "LIBC_FATAL_STDERR_", "1" }
440 };
441
442 static int
443 set_env_action(char *a0)
444 {
445   struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
446   char *a = (char *)(r+1);
447   strcpy(a, a0);
448
449   char *sep = strchr(a, '=');
450   if (sep == a)
451     return 0;
452   r->var = a;
453   if (sep)
454     {
455       *sep++ = 0;
456       r->val = sep;
457     }
458   else
459     r->val = NULL;
460   *last_env_rule = r;
461   last_env_rule = &r->next;
462   r->next = NULL;
463   return 1;
464 }
465
466 static int
467 match_env_var(char *env_entry, struct env_rule *r)
468 {
469   if (strncmp(env_entry, r->var, r->var_len))
470     return 0;
471   return (env_entry[r->var_len] == '=');
472 }
473
474 static void
475 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
476 {
477   // First remove the variable if already set
478   int pos = 0;
479   while (pos < *env_sizep && !match_env_var(env[pos], r))
480     pos++;
481   if (pos < *env_sizep)
482     {
483       (*env_sizep)--;
484       env[pos] = env[*env_sizep];
485       env[*env_sizep] = NULL;
486     }
487
488   // What is the new value?
489   char *new;
490   if (r->val)
491     {
492       if (!r->val[0])
493         return;
494       new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
495       sprintf(new, "%s=%s", r->var, r->val);
496     }
497   else
498     {
499       pos = 0;
500       while (environ[pos] && !match_env_var(environ[pos], r))
501         pos++;
502       if (!(new = environ[pos]))
503         return;
504     }
505
506   // Add it at the end of the array
507   env[(*env_sizep)++] = new;
508   env[*env_sizep] = NULL;
509 }
510
511 static char **
512 setup_environment(void)
513 {
514   // Link built-in rules with user rules
515   for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
516     {
517       default_env_rules[i].next = first_env_rule;
518       first_env_rule = &default_env_rules[i];
519     }
520
521   // Scan the original environment
522   char **orig_env = environ;
523   int orig_size = 0;
524   while (orig_env[orig_size])
525     orig_size++;
526
527   // For each rule, reserve one more slot and calculate length
528   int num_rules = 0;
529   for (struct env_rule *r = first_env_rule; r; r=r->next)
530     {
531       num_rules++;
532       r->var_len = strlen(r->var);
533     }
534
535   // Create a new environment
536   char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
537   int size;
538   if (pass_environ)
539     {
540       memcpy(env, environ, orig_size * sizeof(char *));
541       size = orig_size;
542     }
543   else
544     size = 0;
545   env[size] = NULL;
546
547   // Apply the rules one by one
548   for (struct env_rule *r = first_env_rule; r; r=r->next)
549     apply_env_rule(env, &size, r);
550
551   // Return the new env and pass some gossip
552   if (verbose > 1)
553     {
554       fprintf(stderr, "Passing environment:\n");
555       for (int i=0; env[i]; i++)
556         fprintf(stderr, "\t%s\n", env[i]);
557     }
558   return env;
559 }
560
561 /*** Syscall checks ***/
562
563 static void
564 valid_filename(unsigned long addr)
565 {
566   char namebuf[4096], *p, *end;
567   static int mem_fd;
568
569   if (!file_access)
570     die("File access forbidden");
571   if (file_access >= 9)
572     return;
573
574   if (!mem_fd)
575     {
576       sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
577       mem_fd = open(namebuf, O_RDONLY);
578       if (mem_fd < 0)
579         die("open(%s): %m", namebuf);
580     }
581   p = end = namebuf;
582   do
583     {
584       if (p >= end)
585         {
586           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
587           int l = namebuf + sizeof(namebuf) - end;
588           if (l > remains)
589             l = remains;
590           if (!l)
591             die("Access to file with name too long");
592           if (long_seek(mem_fd, addr, SEEK_SET) < 0)
593             die("long_seek(mem): %m");
594           remains = read(mem_fd, end, l);
595           if (remains < 0)
596             die("read(mem): %m");
597           if (!remains)
598             die("Access to file with name out of memory");
599           end += l;
600           addr += l;
601         }
602     }
603   while (*p++);
604
605   msg("[%s] ", namebuf);
606   if (file_access >= 3)
607     return;
608
609   // Everything in current directory is permitted
610   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
611     return;
612
613   // ".." anywhere in the path is forbidden
614   enum action act = A_DEFAULT;
615   if (strstr(namebuf, ".."))
616     act = A_NO;
617
618   // Scan user rules
619   for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
620     act = match_path_rule(r, namebuf);
621
622   // Scan built-in rules
623   if (file_access >= 2)
624     for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
625       act = match_path_rule(&default_path_rules[i], namebuf);
626
627   if (act != A_YES)
628     die("Forbidden access to file `%s'", namebuf);
629 }
630
631 static int
632 valid_syscall(struct user *u)
633 {
634   unsigned int sys = u->regs.orig_eax;
635   enum action act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
636
637   if (act & A_LIBERAL)
638     {
639       if (filter_syscalls == 1)
640         act &= ~A_LIBERAL;
641       else
642         act = A_DEFAULT;
643     }
644   switch (act)
645     {
646     case A_YES:
647       return 1;
648     case A_NO:
649       return 0;
650     case A_FILENAME:
651       valid_filename(u->regs.ebx);
652       return 1;
653     default: ;
654     }
655
656   switch (sys)
657     {
658     case __NR_kill:
659       if (u->regs.ebx == box_pid)
660         die("Committed suicide by signal %d", (int)u->regs.ecx);
661       return 0;
662     case __NR_tgkill:
663       if (u->regs.ebx == box_pid && u->regs.ecx == box_pid)
664         die("Committed suicide by signal %d", (int)u->regs.edx);
665       return 0;
666     default:
667       return 0;
668     }
669 }
670
671 static void
672 signal_alarm(int unused UNUSED)
673 {
674   /* Time limit checks are synchronous, so we only schedule them there. */
675   timer_tick = 1;
676   alarm(1);
677 }
678
679 static void
680 signal_int(int unused UNUSED)
681 {
682   /* Interrupts are fatal, so no synchronization requirements. */
683   die("Interrupted");
684 }
685
686 static void
687 check_timeout(void)
688 {
689   if (wall_timeout)
690     {
691       struct timeval now, wall;
692       int wall_ms;
693       gettimeofday(&now, NULL);
694       timersub(&now, &start_time, &wall);
695       wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
696       if (wall_ms > wall_timeout)
697         die("Time limit exceeded (wall clock)");
698       if (verbose > 1)
699         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
700     }
701   if (timeout)
702     {
703       char buf[4096], *x;
704       int c, utime, stime, ms;
705       static int proc_status_fd;
706       if (!proc_status_fd)
707         {
708           sprintf(buf, "/proc/%d/stat", (int) box_pid);
709           proc_status_fd = open(buf, O_RDONLY);
710           if (proc_status_fd < 0)
711             die("open(%s): %m", buf);
712         }
713       lseek(proc_status_fd, 0, SEEK_SET);
714       if ((c = read(proc_status_fd, buf, sizeof(buf)-1)) < 0)
715         die("read on /proc/$pid/stat: %m");
716       if (c >= (int) sizeof(buf) - 1)
717         die("/proc/$pid/stat too long");
718       buf[c] = 0;
719       x = buf;
720       while (*x && *x != ' ')
721         x++;
722       while (*x == ' ')
723         x++;
724       if (*x++ != '(')
725         die("proc syntax error 1");
726       while (*x && (*x != ')' || x[1] != ' '))
727         x++;
728       while (*x == ')' || *x == ' ')
729         x++;
730       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
731         die("proc syntax error 2");
732       ms = (utime + stime) * 1000 / ticks_per_sec;
733       if (verbose > 1)
734         fprintf(stderr, "[time check: %d msec]\n", ms);
735       if (ms > timeout)
736         die("Time limit exceeded");
737     }
738 }
739
740 static void
741 boxkeeper(void)
742 {
743   int syscall_count = 0;
744   struct sigaction sa;
745
746   is_ptraced = 1;
747   bzero(&sa, sizeof(sa));
748   sa.sa_handler = signal_int;
749   sigaction(SIGINT, &sa, NULL);
750   gettimeofday(&start_time, NULL);
751   ticks_per_sec = sysconf(_SC_CLK_TCK);
752   if (ticks_per_sec <= 0)
753     die("Invalid ticks_per_sec!");
754   if (timeout || wall_timeout)
755     {
756       sa.sa_handler = signal_alarm;
757       sigaction(SIGALRM, &sa, NULL);
758       alarm(1);
759     }
760   for(;;)
761     {
762       struct rusage rus;
763       int stat;
764       pid_t p;
765       if (timer_tick)
766         {
767           check_timeout();
768           timer_tick = 0;
769         }
770       p = wait4(box_pid, &stat, WUNTRACED, &rus);
771       if (p < 0)
772         {
773           if (errno == EINTR)
774             continue;
775           die("wait4: %m");
776         }
777       if (p != box_pid)
778         die("wait4: unknown pid %d exited!", p);
779       if (WIFEXITED(stat))
780         {
781           box_pid = 0;
782           final_stats(&rus);
783           // FIXME: If the process has exited before being ptraced, signal an internal error
784           if (WEXITSTATUS(stat))
785             die("Exited with error status %d", WEXITSTATUS(stat));
786           if (timeout && total_ms > timeout)
787             die("Time limit exceeded");
788           if (wall_timeout && wall_ms > wall_timeout)
789             die("Time limit exceeded (wall clock)");
790           flush_line();
791           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d syscalls)\n",
792               total_ms/1000, total_ms%1000,
793               wall_ms/1000, wall_ms%1000,
794               syscall_count);
795           box_exit(0);
796         }
797       if (WIFSIGNALED(stat))
798         {
799           box_pid = 0;
800           die("Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
801         }
802       if (WIFSTOPPED(stat))
803         {
804           int sig = WSTOPSIG(stat);
805           if (sig == SIGTRAP)
806             {
807               struct user u;
808               static int stop_count = -1;
809               if (ptrace(PTRACE_GETREGS, box_pid, NULL, &u) < 0)
810                 die("ptrace(PTRACE_GETREGS): %m");
811               stop_count++;
812               if (!stop_count)                  /* Traceme request */
813                 msg(">> Traceme request caught\n");
814               else if (stop_count & 1)          /* Syscall entry */
815                 {
816                   char namebuf[32];
817                   msg(">> Syscall %-12s (%08lx,%08lx,%08lx) ", syscall_name(u.regs.orig_eax, namebuf), u.regs.ebx, u.regs.ecx, u.regs.edx);
818                   if (!exec_seen)
819                     {
820                       msg("[master] ");
821                       if (u.regs.orig_eax == __NR_execve)
822                         exec_seen = 1;
823                     }
824                   else if (valid_syscall(&u))
825                     syscall_count++;
826                   else
827                     {
828                       /*
829                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
830                        * so we have to change it to something harmless (e.g., an undefined
831                        * syscall) and make the program continue.
832                        */
833                       unsigned int sys = u.regs.orig_eax;
834                       u.regs.orig_eax = 0xffffffff;
835                       if (ptrace(PTRACE_SETREGS, box_pid, NULL, &u) < 0)
836                         die("ptrace(PTRACE_SETREGS): %m");
837                       die("Forbidden syscall %s", syscall_name(sys, namebuf));
838                     }
839                 }
840               else                                      /* Syscall return */
841                 msg("= %ld\n", u.regs.eax);
842               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
843             }
844           else if (sig != SIGSTOP && sig != SIGXCPU && sig != SIGXFSZ)
845             {
846               msg(">> Signal %d\n", sig);
847               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
848             }
849           else
850             die("Received signal %d", sig);
851         }
852       else
853         die("wait4: unknown status %x, giving up!", stat);
854     }
855 }
856
857 static void
858 box_inside(int argc, char **argv)
859 {
860   struct rlimit rl;
861   char *args[argc+1];
862
863   memcpy(args, argv, argc * sizeof(char *));
864   args[argc] = NULL;
865   if (set_cwd && chdir(set_cwd))
866     die("chdir: %m");
867   if (redir_stdin)
868     {
869       close(0);
870       if (open(redir_stdin, O_RDONLY) != 0)
871         die("open(\"%s\"): %m", redir_stdin);
872     }
873   if (redir_stdout)
874     {
875       close(1);
876       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
877         die("open(\"%s\"): %m", redir_stdout);
878     }
879   if (redir_stderr)
880     {
881       close(2);
882       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
883         die("open(\"%s\"): %m", redir_stderr);
884     }
885   else
886     dup2(1, 2);
887   setpgrp();
888   if (memory_limit)
889     {
890       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
891       if (setrlimit(RLIMIT_AS, &rl) < 0)
892         die("setrlimit: %m");
893     }
894   rl.rlim_cur = rl.rlim_max = 64;
895   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
896     die("setrlimit: %m");
897   if (filter_syscalls)
898     {
899       if (ptrace(PTRACE_TRACEME) < 0)
900         die("ptrace(PTRACE_TRACEME): %m");
901       /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
902       signal(SIGCHLD, SIG_IGN);
903       raise(SIGCHLD);
904     }
905   execve(args[0], args, setup_environment());
906   die("execve(\"%s\"): %m", args[0]);
907 }
908
909 static void
910 usage(void)
911 {
912   fprintf(stderr, "Invalid arguments!\n");
913   printf("\
914 Usage: box [<options>] -- <command> <arguments>\n\
915 \n\
916 Options:\n\
917 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
918 -c <dir>\tChange directory to <dir> first\n\
919 -e\t\tInherit full environment of the parent process\n\
920 -E <var>\tInherit the environment variable <var> from the parent process\n\
921 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
922 -f\t\tFilter system calls (-ff=very restricted)\n\
923 -i <file>\tRedirect stdin from <file>\n\
924 -m <size>\tLimit address space to <size> KB\n\
925 -M <file>\tOutput process information to <file> (name:value)\n\
926 -o <file>\tRedirect stdout to <file>\n\
927 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
928 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
929 -r <file>\tRedirect stderr to <file>\n\
930 -s <sys>\tPermit the specified syscall (be careful)\n\
931 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
932 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
933 -T\t\tAllow syscalls for measuring run time\n\
934 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
935 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
936 ");
937   exit(1);
938 }
939
940 int
941 main(int argc, char **argv)
942 {
943   int c;
944   uid_t uid;
945
946   while ((c = getopt(argc, argv, "a:c:eE:fi:m:M:o:p:r:s:t:Tvw:")) >= 0)
947     switch (c)
948       {
949       case 'a':
950         file_access = atol(optarg);
951         break;
952       case 'c':
953         set_cwd = optarg;
954         break;
955       case 'e':
956         pass_environ = 1;
957         break;
958       case 'E':
959         if (!set_env_action(optarg))
960           usage();
961         break;
962       case 'f':
963         filter_syscalls++;
964         break;
965       case 'i':
966         redir_stdin = optarg;
967         break;
968       case 'm':
969         memory_limit = atol(optarg);
970         break;
971       case 'M':
972         meta_open(optarg);
973         break;
974       case 'o':
975         redir_stdout = optarg;
976         break;
977       case 'p':
978         if (!set_path_action(optarg))
979           usage();
980         break;
981       case 'r':
982         redir_stderr = optarg;
983         break;
984       case 's':
985         if (!set_syscall_action(optarg))
986           usage();
987         break;
988       case 't':
989         timeout = 1000*atof(optarg);
990         break;
991       case 'T':
992         syscall_action[__NR_times] = A_YES;
993         break;
994       case 'v':
995         verbose++;
996         break;
997       case 'w':
998         wall_timeout = 1000*atof(optarg);
999         break;
1000       default:
1001         usage();
1002       }
1003   if (optind >= argc)
1004     usage();
1005
1006   uid = geteuid();
1007   if (setreuid(uid, uid) < 0)
1008     die("setreuid: %m");
1009   box_pid = fork();
1010   if (box_pid < 0)
1011     die("fork: %m");
1012   if (!box_pid)
1013     box_inside(argc-optind, argv+optind);
1014   else
1015     boxkeeper();
1016   die("Internal error: fell over edge of the world");
1017 }