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