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