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