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