]> mj.ucw.cz Git - eval.git/blob - box/box.c
MO-P: Let KDE template contain a confirmed server certificate
[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 user_mem_fd;
627
628 static int read_user_mem(arg_t addr, char *buf, int len)
629 {
630   if (!user_mem_fd)
631     {
632       char memname[64];
633       sprintf(memname, "/proc/%d/mem", (int) box_pid);
634       user_mem_fd = open(memname, O_RDONLY);
635       if (user_mem_fd < 0)
636         die("open(%s): %m", memname);
637     }
638   if (lseek64(user_mem_fd, addr, SEEK_SET) < 0)
639     die("lseek64(mem): %m");
640   return read(user_mem_fd, buf, len);
641 }
642
643 static void close_user_mem(void)
644 {
645   if (user_mem_fd)
646     {
647       close(user_mem_fd);
648       user_mem_fd = 0;
649     }
650 }
651
652 #ifdef CONFIG_BOX_KERNEL_AMD64
653
654 static void
655 get_syscall_args(struct syscall_args *a, int is_exit)
656 {
657   if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
658     die("ptrace(PTRACE_GETREGS): %m");
659   a->sys = a->user.regs.orig_rax;
660   a->result = a->user.regs.rax;
661
662   /*
663    *  CAVEAT: We have to check carefully that this is a real 64-bit syscall.
664    *  We test whether the process runs in 64-bit mode, but surprisingly this
665    *  is not enough: a 64-bit process can still issue the INT 0x80 instruction
666    *  which performs a 32-bit syscall. Currently, the only known way how to
667    *  detect this situation is to inspect the instruction code (the kernel
668    *  keeps a syscall type flag internally, but it is not accessible from
669    *  user space). Hopefully, there is no instruction whose suffix is the
670    *  code of the SYSCALL instruction. Sometimes, one would wish the
671    *  instruction codes to be unique even when read backwards :)
672    */
673
674   if (is_exit)
675     return;
676
677   int sys_type;
678   uint16_t instr;
679
680   switch (a->user.regs.cs)
681     {
682     case 0x23:
683       // 32-bit CPU mode => only 32-bit syscalls can be issued
684       sys_type = 32;
685       break;
686     case 0x33:
687       // 64-bit CPU mode
688       if (read_user_mem(a->user.regs.rip-2, (char *) &instr, 2) != 2)
689         err("FO: Cannot read syscall instruction");
690       switch (instr)
691         {
692         case 0x050f:
693           break;
694         case 0x80cd:
695           err("FO: Forbidden 32-bit syscall in 64-bit mode");
696         default:
697           err("XX: Unknown syscall instruction %04x", instr);
698         }
699       sys_type = 64;
700       break;
701     default:
702       err("XX: Unknown code segment %04jx", (intmax_t) a->user.regs.cs);
703     }
704
705 #ifdef CONFIG_BOX_USER_AMD64
706   if (sys_type != 64)
707     err("FO: Forbidden %d-bit mode syscall", sys_type);
708 #else
709   if (sys_type != (exec_seen ? 32 : 64))
710     err("FO: Forbidden %d-bit mode syscall", sys_type);
711 #endif
712
713   if (sys_type == 32)
714     {
715       a->arg1 = a->user.regs.rbx;
716       a->arg2 = a->user.regs.rcx;
717       a->arg3 = a->user.regs.rdx;
718     }
719   else
720     {
721       a->arg1 = a->user.regs.rdi;
722       a->arg2 = a->user.regs.rsi;
723       a->arg3 = a->user.regs.rdx;
724     }
725 }
726
727 static void
728 set_syscall_nr(struct syscall_args *a, arg_t sys)
729 {
730   a->sys = sys;
731   a->user.regs.orig_rax = sys;
732   if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
733     die("ptrace(PTRACE_SETREGS): %m");
734 }
735
736 static void
737 sanity_check(void)
738 {
739 }
740
741 #else
742
743 static void
744 get_syscall_args(struct syscall_args *a, int is_exit UNUSED)
745 {
746   if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
747     die("ptrace(PTRACE_GETREGS): %m");
748   a->sys = a->user.regs.orig_eax;
749   a->arg1 = a->user.regs.ebx;
750   a->arg2 = a->user.regs.ecx;
751   a->arg3 = a->user.regs.edx;
752   a->result = a->user.regs.eax;
753 }
754
755 static void
756 set_syscall_nr(struct syscall_args *a, arg_t sys)
757 {
758   a->sys = sys;
759   a->user.regs.orig_eax = sys;
760   if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
761     die("ptrace(PTRACE_SETREGS): %m");
762 }
763
764 static void
765 sanity_check(void)
766 {
767 #if !defined(CONFIG_BOX_ALLOW_INSECURE)
768   struct utsname uts;
769   if (uname(&uts) < 0)
770     die("uname() failed: %m");
771
772   if (!strcmp(uts.machine, "x86_64"))
773     die("Running 32-bit sandbox on 64-bit kernels is inherently unsafe. Please get a 64-bit version.");
774 #endif
775 }
776
777 #endif
778
779 /*** Syscall checks ***/
780
781 static void
782 valid_filename(arg_t addr)
783 {
784   char namebuf[4096], *p, *end;
785
786   if (!file_access)
787     err("FA: File access forbidden");
788   if (file_access >= 9)
789     return;
790
791   p = end = namebuf;
792   do
793     {
794       if (p >= end)
795         {
796           int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
797           int l = namebuf + sizeof(namebuf) - end;
798           if (l > remains)
799             l = remains;
800           if (!l)
801             err("FA: Access to file with name too long");
802           remains = read_user_mem(addr, end, l);
803           if (remains < 0)
804             die("read(mem): %m");
805           if (!remains)
806             err("FA: Access to file with name out of memory");
807           end += remains;
808           addr += remains;
809         }
810     }
811   while (*p++);
812
813   msg("[%s] ", namebuf);
814   if (file_access >= 3)
815     return;
816
817   // Everything in current directory is permitted
818   if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
819     return;
820
821   // ".." anywhere in the path is forbidden
822   enum action act = A_DEFAULT;
823   if (strstr(namebuf, ".."))
824     act = A_NO;
825
826   // Scan user rules
827   for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
828     act = match_path_rule(r, namebuf);
829
830   // Scan built-in rules
831   if (file_access >= 2)
832     for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
833       act = match_path_rule(&default_path_rules[i], namebuf);
834
835   if (act != A_YES)
836     err("FA: Forbidden access to file `%s'", namebuf);
837 }
838
839 // Check syscall. If invalid, return -1, otherwise return the action mask.
840 static int
841 valid_syscall(struct syscall_args *a)
842 {
843   unsigned int sys = a->sys;
844   unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
845
846   if (act & A_LIBERAL)
847     {
848       if (filter_syscalls != 1)
849         act = A_DEFAULT;
850     }
851
852   switch (act & A_ACTION_MASK)
853     {
854     case A_YES:
855       return act;
856     case A_NO:
857       return -1;
858     case A_FILENAME:
859       valid_filename(a->arg1);
860       return act;
861     default: ;
862     }
863
864   switch (sys)
865     {
866     case __NR_kill:
867       if (a->arg1 == (arg_t) box_pid)
868         {
869           meta_printf("exitsig:%d\n", (int) a->arg2);
870           err("SG: Committed suicide by signal %d", (int) a->arg2);
871         }
872       return -1;
873     case __NR_tgkill:
874       if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
875         {
876           meta_printf("exitsig:%d\n", (int) a->arg3);
877           err("SG: Committed suicide by signal %d", (int) a->arg3);
878         }
879       return -1;
880     default:
881       return -1;
882     }
883 }
884
885 static void
886 signal_alarm(int unused UNUSED)
887 {
888   /* Time limit checks are synchronous, so we only schedule them there. */
889   timer_tick = 1;
890   alarm(1);
891 }
892
893 static void
894 signal_int(int unused UNUSED)
895 {
896   /* Interrupts are fatal, so no synchronization requirements. */
897   meta_printf("exitsig:%d\n", SIGINT);
898   err("SG: Interrupted");
899 }
900
901 #define PROC_BUF_SIZE 4096
902 static void
903 read_proc_file(char *buf, char *name, int *fdp)
904 {
905   int c;
906
907   if (!*fdp)
908     {
909       sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
910       *fdp = open(buf, O_RDONLY);
911       if (*fdp < 0)
912         die("open(%s): %m", buf);
913     }
914   lseek(*fdp, 0, SEEK_SET);
915   if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
916     die("read on /proc/$pid/%s: %m", name);
917   if (c >= PROC_BUF_SIZE-1)
918     die("/proc/$pid/%s too long", name);
919   buf[c] = 0;
920 }
921
922 static void
923 check_timeout(void)
924 {
925   if (wall_timeout)
926     {
927       struct timeval now, wall;
928       int wall_ms;
929       gettimeofday(&now, NULL);
930       timersub(&now, &start_time, &wall);
931       wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
932       if (wall_ms > wall_timeout)
933         err("TO: Time limit exceeded (wall clock)");
934       if (verbose > 1)
935         fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
936     }
937   if (timeout)
938     {
939       char buf[PROC_BUF_SIZE], *x;
940       int utime, stime, ms;
941       static int proc_stat_fd;
942       read_proc_file(buf, "stat", &proc_stat_fd);
943       x = buf;
944       while (*x && *x != ' ')
945         x++;
946       while (*x == ' ')
947         x++;
948       if (*x++ != '(')
949         die("proc stat syntax error 1");
950       while (*x && (*x != ')' || x[1] != ' '))
951         x++;
952       while (*x == ')' || *x == ' ')
953         x++;
954       if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
955         die("proc stat syntax error 2");
956       ms = (utime + stime) * 1000 / ticks_per_sec;
957       if (verbose > 1)
958         fprintf(stderr, "[time check: %d msec]\n", ms);
959       if (ms > timeout && ms > extra_timeout)
960         err("TO: Time limit exceeded");
961     }
962 }
963
964 static void
965 sample_mem_peak(void)
966 {
967   /*
968    *  We want to find out the peak memory usage of the process, which is
969    *  maintained by the kernel, but unforunately it gets lost when the
970    *  process exits (it is not reported in struct rusage). Therefore we
971    *  have to sample it whenever we suspect that the process is about
972    *  to exit.
973    */
974   char buf[PROC_BUF_SIZE], *x;
975   static int proc_status_fd;
976   read_proc_file(buf, "status", &proc_status_fd);
977
978   x = buf;
979   while (*x)
980     {
981       char *key = x;
982       while (*x && *x != ':' && *x != '\n')
983         x++;
984       if (!*x || *x == '\n')
985         break;
986       *x++ = 0;
987       while (*x == ' ' || *x == '\t')
988         x++;
989
990       char *val = x;
991       while (*x && *x != '\n')
992         x++;
993       if (!*x)
994         break;
995       *x++ = 0;
996
997       if (!strcmp(key, "VmPeak"))
998         {
999           int peak = atoi(val);
1000           if (peak > mem_peak_kb)
1001             mem_peak_kb = peak;
1002         }
1003     }
1004
1005   if (verbose > 1)
1006     msg("[mem-peak: %u KB]\n", mem_peak_kb);
1007 }
1008
1009 static void
1010 boxkeeper(void)
1011 {
1012   int syscall_count = (filter_syscalls ? 0 : 1);
1013   struct sigaction sa;
1014
1015   is_ptraced = 1;
1016
1017   bzero(&sa, sizeof(sa));
1018   sa.sa_handler = signal_int;
1019   sigaction(SIGINT, &sa, NULL);
1020
1021   gettimeofday(&start_time, NULL);
1022   ticks_per_sec = sysconf(_SC_CLK_TCK);
1023   if (ticks_per_sec <= 0)
1024     die("Invalid ticks_per_sec!");
1025
1026   if (timeout || wall_timeout)
1027     {
1028       sa.sa_handler = signal_alarm;
1029       sigaction(SIGALRM, &sa, NULL);
1030       alarm(1);
1031     }
1032
1033   for(;;)
1034     {
1035       struct rusage rus;
1036       int stat;
1037       pid_t p;
1038       if (timer_tick)
1039         {
1040           check_timeout();
1041           timer_tick = 0;
1042         }
1043       p = wait4(box_pid, &stat, WUNTRACED, &rus);
1044       if (p < 0)
1045         {
1046           if (errno == EINTR)
1047             continue;
1048           die("wait4: %m");
1049         }
1050       if (p != box_pid)
1051         die("wait4: unknown pid %d exited!", p);
1052       if (WIFEXITED(stat))
1053         {
1054           box_pid = 0;
1055           final_stats(&rus);
1056           if (WEXITSTATUS(stat))
1057             {
1058               if (syscall_count)
1059                 {
1060                   meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1061                   err("RE: Exited with error status %d", WEXITSTATUS(stat));
1062                 }
1063               else
1064                 {
1065                   // Internal error happened inside the child process and it has been already reported.
1066                   box_exit(2);
1067                 }
1068             }
1069           if (timeout && total_ms > timeout)
1070             err("TO: Time limit exceeded");
1071           if (wall_timeout && wall_ms > wall_timeout)
1072             err("TO: Time limit exceeded (wall clock)");
1073           flush_line();
1074           fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
1075               total_ms/1000, total_ms%1000,
1076               wall_ms/1000, wall_ms%1000,
1077               (mem_peak_kb + 1023) / 1024,
1078               syscall_count);
1079           box_exit(0);
1080         }
1081       if (WIFSIGNALED(stat))
1082         {
1083           box_pid = 0;
1084           meta_printf("exitsig:%d\n", WTERMSIG(stat));
1085           final_stats(&rus);
1086           err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
1087         }
1088       if (WIFSTOPPED(stat))
1089         {
1090           int sig = WSTOPSIG(stat);
1091           if (sig == SIGTRAP)
1092             {
1093               if (verbose > 2)
1094                 msg("[ptrace status %08x] ", stat);
1095               static int stop_count;
1096               if (!stop_count++)                /* Traceme request */
1097                 msg(">> Traceme request caught\n");
1098               else
1099                 err("SG: Breakpoint");
1100               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1101             }
1102           else if (sig == (SIGTRAP | 0x80))
1103             {
1104               if (verbose > 2)
1105                 msg("[ptrace status %08x] ", stat);
1106               struct syscall_args a;
1107               static unsigned int sys_tick, last_act;
1108               static arg_t last_sys;
1109               if (++sys_tick & 1)               /* Syscall entry */
1110                 {
1111                   char namebuf[32];
1112                   int act;
1113
1114                   get_syscall_args(&a, 0);
1115                   arg_t sys = a.sys;
1116                   msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1117                   if (!exec_seen)
1118                     {
1119                       msg("[master] ");
1120                       if (sys == NATIVE_NR_execve)
1121                         {
1122                           exec_seen = 1;
1123                           close_user_mem();
1124                         }
1125                     }
1126                   else if ((act = valid_syscall(&a)) >= 0)
1127                     {
1128                       last_act = act;
1129                       syscall_count++;
1130                       if (act & A_SAMPLE_MEM)
1131                         sample_mem_peak();
1132                     }
1133                   else
1134                     {
1135                       /*
1136                        * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1137                        * so we have to change it to something harmless (e.g., an undefined
1138                        * syscall) and make the program continue.
1139                        */
1140                       set_syscall_nr(&a, ~(arg_t)0);
1141                       err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1142                     }
1143                   last_sys = sys;
1144                 }
1145               else                                      /* Syscall return */
1146                 {
1147                   get_syscall_args(&a, 1);
1148                   if (a.sys == ~(arg_t)0)
1149                     {
1150                       /* Some syscalls (sigreturn et al.) do not return a value */
1151                       if (!(last_act & A_NO_RETVAL))
1152                         err("XX: Syscall does not return, but it should");
1153                     }
1154                   else
1155                     {
1156                       if (a.sys != last_sys)
1157                         err("XX: Mismatched syscall entry/exit");
1158                     }
1159                   if (last_act & A_NO_RETVAL)
1160                     msg("= ?\n");
1161                   else
1162                     msg("= %jd\n", (intmax_t) a.result);
1163                 }
1164               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1165             }
1166           else if (sig == SIGSTOP)
1167             {
1168               msg(">> SIGSTOP\n");
1169               if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1170                 die("ptrace(PTRACE_SETOPTIONS): %m");
1171               ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1172             }
1173           else if (sig != SIGXCPU && sig != SIGXFSZ)
1174             {
1175               msg(">> Signal %d\n", sig);
1176               sample_mem_peak();                        /* Signal might be fatal, so update mem-peak */
1177               ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1178             }
1179           else
1180             {
1181               meta_printf("exitsig:%d", sig);
1182               err("SG: Received signal %d", sig);
1183             }
1184         }
1185       else
1186         die("wait4: unknown status %x, giving up!", stat);
1187     }
1188 }
1189
1190 static void
1191 box_inside(int argc, char **argv)
1192 {
1193   struct rlimit rl;
1194   char *args[argc+1];
1195
1196   memcpy(args, argv, argc * sizeof(char *));
1197   args[argc] = NULL;
1198   if (set_cwd && chdir(set_cwd))
1199     die("chdir: %m");
1200   if (redir_stdin)
1201     {
1202       close(0);
1203       if (open(redir_stdin, O_RDONLY) != 0)
1204         die("open(\"%s\"): %m", redir_stdin);
1205     }
1206   if (redir_stdout)
1207     {
1208       close(1);
1209       if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1210         die("open(\"%s\"): %m", redir_stdout);
1211     }
1212   if (redir_stderr)
1213     {
1214       close(2);
1215       if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1216         die("open(\"%s\"): %m", redir_stderr);
1217     }
1218   else
1219     dup2(1, 2);
1220   setpgrp();
1221
1222   if (memory_limit)
1223     {
1224       rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1225       if (setrlimit(RLIMIT_AS, &rl) < 0)
1226         die("setrlimit(RLIMIT_AS): %m");
1227     }
1228
1229   rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1230   if (setrlimit(RLIMIT_STACK, &rl) < 0)
1231     die("setrlimit(RLIMIT_STACK): %m");
1232
1233   rl.rlim_cur = rl.rlim_max = 64;
1234   if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1235     die("setrlimit(RLIMIT_NOFILE): %m");
1236
1237   char **env = setup_environment();
1238   if (filter_syscalls)
1239     {
1240       if (ptrace(PTRACE_TRACEME) < 0)
1241         die("ptrace(PTRACE_TRACEME): %m");
1242       /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1243       raise(SIGSTOP);
1244     }
1245   execve(args[0], args, env);
1246   die("execve(\"%s\"): %m", args[0]);
1247 }
1248
1249 static void
1250 usage(void)
1251 {
1252   fprintf(stderr, "Invalid arguments!\n");
1253   printf("\
1254 Usage: box [<options>] -- <command> <arguments>\n\
1255 \n\
1256 Options:\n\
1257 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1258 -c <dir>\tChange directory to <dir> first\n\
1259 -e\t\tInherit full environment of the parent process\n\
1260 -E <var>\tInherit the environment variable <var> from the parent process\n\
1261 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1262 -f\t\tFilter system calls (-ff=very restricted)\n\
1263 -i <file>\tRedirect stdin from <file>\n\
1264 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1265 -m <size>\tLimit address space to <size> KB\n\
1266 -M <file>\tOutput process information to <file> (name:value)\n\
1267 -o <file>\tRedirect stdout to <file>\n\
1268 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1269 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1270 -r <file>\tRedirect stderr to <file>\n\
1271 -s <sys>\tPermit the specified syscall (be careful)\n\
1272 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1273 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1274 -T\t\tAllow syscalls for measuring run time\n\
1275 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1276 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1277 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1278 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1279 ");
1280   exit(2);
1281 }
1282
1283 int
1284 main(int argc, char **argv)
1285 {
1286   int c;
1287   uid_t uid;
1288
1289   while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1290     switch (c)
1291       {
1292       case 'a':
1293         file_access = atol(optarg);
1294         break;
1295       case 'c':
1296         set_cwd = optarg;
1297         break;
1298       case 'e':
1299         pass_environ = 1;
1300         break;
1301       case 'E':
1302         if (!set_env_action(optarg))
1303           usage();
1304         break;
1305       case 'f':
1306         filter_syscalls++;
1307         break;
1308       case 'k':
1309         stack_limit = atol(optarg);
1310         break;
1311       case 'i':
1312         redir_stdin = optarg;
1313         break;
1314       case 'm':
1315         memory_limit = atol(optarg);
1316         break;
1317       case 'M':
1318         meta_open(optarg);
1319         break;
1320       case 'o':
1321         redir_stdout = optarg;
1322         break;
1323       case 'p':
1324         if (!set_path_action(optarg))
1325           usage();
1326         break;
1327       case 'r':
1328         redir_stderr = optarg;
1329         break;
1330       case 's':
1331         if (!set_syscall_action(optarg))
1332           usage();
1333         break;
1334       case 't':
1335         timeout = 1000*atof(optarg);
1336         break;
1337       case 'T':
1338         syscall_action[__NR_times] = A_YES;
1339         break;
1340       case 'v':
1341         verbose++;
1342         break;
1343       case 'w':
1344         wall_timeout = 1000*atof(optarg);
1345         break;
1346       case 'x':
1347         extra_timeout = 1000*atof(optarg);
1348         break;
1349       default:
1350         usage();
1351       }
1352   if (optind >= argc)
1353     usage();
1354
1355   sanity_check();
1356   uid = geteuid();
1357   if (setreuid(uid, uid) < 0)
1358     die("setreuid: %m");
1359   box_pid = fork();
1360   if (box_pid < 0)
1361     die("fork: %m");
1362   if (!box_pid)
1363     box_inside(argc-optind, argv+optind);
1364   else
1365     boxkeeper();
1366   die("Internal error: fell over edge of the world");
1367 }