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