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