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