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