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