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