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