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