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