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