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