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