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