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