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