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