2 * A Simple Sandbox for Moe
4 * (c) 2001--2010 Martin Mares <mj@ucw.cz>
7 #define _LARGEFILE64_SOURCE
23 #include <sys/ptrace.h>
24 #include <sys/signal.h>
25 #include <sys/sysinfo.h>
26 #include <sys/syscall.h>
27 #include <sys/resource.h>
28 #include <linux/ptrace.h>
30 #define NONRET __attribute__((noreturn))
31 #define UNUSED __attribute__((unused))
32 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
34 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
35 static int timeout; /* milliseconds */
36 static int wall_timeout;
37 static int extra_timeout;
38 static int pass_environ;
39 static int file_access;
41 static int memory_limit;
42 static int stack_limit;
43 static char *redir_stdin, *redir_stdout, *redir_stderr;
47 static int is_ptraced;
48 static volatile int timer_tick;
49 static struct timeval start_time;
50 static int ticks_per_sec;
52 static int partial_line;
54 static int mem_peak_kb;
55 static int total_ms, wall_ms;
57 static void die(char *msg, ...) NONRET;
58 static void sample_mem_peak(void);
62 static FILE *metafile;
65 meta_open(const char *name)
67 if (!strcmp(name, "-"))
72 metafile = fopen(name, "w");
74 die("Failed to open metafile '%s'",name);
80 if (metafile && metafile != stdout)
84 static void __attribute__((format(printf,1,2)))
85 meta_printf(const char *fmt, ...)
92 vfprintf(metafile, fmt, args);
97 final_stats(struct rusage *rus)
99 struct timeval total, now, wall;
100 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
101 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
102 gettimeofday(&now, NULL);
103 timersub(&now, &start_time, &wall);
104 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
106 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
107 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
108 meta_printf("mem:%llu\n", (unsigned long long) mem_peak_kb * 1024);
111 /*** Messages and exits ***/
120 ptrace(PTRACE_KILL, box_pid);
121 kill(-box_pid, SIGKILL);
122 kill(box_pid, SIGKILL);
123 meta_printf("killed:1\n");
128 p = wait4(box_pid, &stat, 0, &rus);
129 while (p < 0 && errno == EINTR);
131 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
147 /* Report an error of the sandbox itself */
148 static void NONRET __attribute__((format(printf,1,2)))
155 vsnprintf(buf, sizeof(buf), msg, args);
156 meta_printf("status:XX\nmessage:%s\n", buf);
162 /* Report an error of the program inside the sandbox */
163 static void NONRET __attribute__((format(printf,1,2)))
169 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
171 meta_printf("status:%c%c\n", msg[0], msg[1]);
175 vsnprintf(buf, sizeof(buf), msg, args);
176 meta_printf("message:%s\n", buf);
182 /* Write a message, but only if in verbose mode */
183 static void __attribute__((format(printf,1,2)))
190 int len = strlen(msg);
192 partial_line = (msg[len-1] != '\n');
193 vfprintf(stderr, msg, args);
202 void *p = malloc(size);
204 die("Out of memory");
208 /*** Syscall rules ***/
210 static const char * const syscall_names[] = {
211 #include "box/syscall-table.h"
213 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
214 #define NUM_ACTIONS (NUM_SYSCALLS+64)
217 A_DEFAULT, // Use the default action
218 A_NO, // Always forbid
219 A_YES, // Always permit
220 A_FILENAME, // Permit if arg1 is a known filename
222 A_NO_RETVAL = 32, // Does not return a value
223 A_SAMPLE_MEM = 64, // Sample memory usage before the syscall
224 A_LIBERAL = 128, // Valid only in liberal mode
225 // Must fit in a unsigned char
228 static unsigned char syscall_action[NUM_ACTIONS] = {
229 #define S(x) [__NR_##x]
231 // Syscalls permitted for specific file names
232 S(open) = A_FILENAME,
233 S(creat) = A_FILENAME,
234 S(unlink) = A_FILENAME,
235 S(access) = A_FILENAME,
236 S(truncate) = A_FILENAME,
237 S(stat) = A_FILENAME,
238 S(lstat) = A_FILENAME,
239 S(readlink) = A_FILENAME,
240 #ifndef CONFIG_BOX_AMD64
241 S(oldstat) = A_FILENAME,
242 S(oldlstat) = A_FILENAME,
243 S(truncate64) = A_FILENAME,
244 S(stat64) = A_FILENAME,
245 S(lstat64) = A_FILENAME,
248 // Syscalls permitted always
249 S(exit) = A_YES | A_SAMPLE_MEM,
262 S(ftruncate) = A_YES,
264 S(personality) = A_YES,
267 S(getresuid) = A_YES,
281 S(set_thread_area) = A_YES,
282 S(get_thread_area) = A_YES,
283 S(set_tid_address) = A_YES,
284 S(exit_group) = A_YES | A_SAMPLE_MEM,
285 #ifndef CONFIG_BOX_AMD64
287 S(ftruncate64) = A_YES,
294 // Syscalls permitted only in liberal mode
295 S(time) = A_YES | A_LIBERAL,
296 S(alarm) = A_YES | A_LIBERAL,
297 S(pause) = A_YES | A_LIBERAL,
298 S(fchmod) = A_YES | A_LIBERAL,
299 S(getrlimit) = A_YES | A_LIBERAL,
300 S(getrusage) = A_YES | A_LIBERAL,
301 S(gettimeofday) = A_YES | A_LIBERAL,
302 S(select) = A_YES | A_LIBERAL,
303 S(setitimer) = A_YES | A_LIBERAL,
304 S(getitimer) = A_YES | A_LIBERAL,
305 S(mprotect) = A_YES | A_LIBERAL,
306 S(getdents) = A_YES | A_LIBERAL,
307 S(getdents64) = A_YES | A_LIBERAL,
308 S(fdatasync) = A_YES | A_LIBERAL,
309 S(mremap) = A_YES | A_LIBERAL,
310 S(poll) = A_YES | A_LIBERAL,
311 S(getcwd) = A_YES | A_LIBERAL,
312 S(nanosleep) = A_YES | A_LIBERAL,
313 S(rt_sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
314 S(rt_sigaction) = A_YES | A_LIBERAL,
315 S(rt_sigprocmask) = A_YES | A_LIBERAL,
316 S(rt_sigpending) = A_YES | A_LIBERAL,
317 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
318 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
319 S(rt_sigsuspend) = A_YES | A_LIBERAL,
320 S(_sysctl) = A_YES | A_LIBERAL,
321 #ifndef CONFIG_BOX_AMD64
322 S(sigaction) = A_YES | A_LIBERAL,
323 S(sgetmask) = A_YES | A_LIBERAL,
324 S(ssetmask) = A_YES | A_LIBERAL,
325 S(sigsuspend) = A_YES | A_LIBERAL,
326 S(sigpending) = A_YES | A_LIBERAL,
327 S(sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
328 S(sigprocmask) = A_YES | A_LIBERAL,
329 S(ugetrlimit) = A_YES | A_LIBERAL,
330 S(readdir) = A_YES | A_LIBERAL,
331 S(signal) = A_YES | A_LIBERAL,
332 S(_newselect) = A_YES | A_LIBERAL,
339 syscall_name(unsigned int id, char *buf)
341 if (id < NUM_SYSCALLS && syscall_names[id])
342 return syscall_names[id];
345 sprintf(buf, "#%d", id);
351 syscall_by_name(char *name)
353 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
354 if (syscall_names[i] && !strcmp(syscall_names[i], name))
361 unsigned long l = strtoul(name, &ep, 0);
364 if (l >= NUM_ACTIONS)
370 set_syscall_action(char *a)
372 char *sep = strchr(a, '=');
373 enum action act = A_YES;
377 if (!strcmp(sep, "yes"))
379 else if (!strcmp(sep, "no"))
381 else if (!strcmp(sep, "file"))
387 int sys = syscall_by_name(a);
389 die("Unknown syscall `%s'", a);
390 if (sys >= NUM_ACTIONS)
391 die("Syscall `%s' out of range", a);
392 syscall_action[sys] = act;
401 struct path_rule *next;
404 static struct path_rule default_path_rules[] = {
407 { "/usr/lib/", A_YES },
408 { "/opt/lib/", A_YES },
409 { "/usr/share/zoneinfo/", A_YES },
410 { "/usr/share/locale/", A_YES },
411 { "/dev/null", A_YES },
412 { "/dev/zero", A_YES },
413 { "/proc/meminfo", A_YES },
414 { "/proc/self/stat", A_YES },
415 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
418 static struct path_rule *user_path_rules;
419 static struct path_rule **last_path_rule = &user_path_rules;
422 set_path_action(char *a)
424 char *sep = strchr(a, '=');
425 enum action act = A_YES;
429 if (!strcmp(sep, "yes"))
431 else if (!strcmp(sep, "no"))
437 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
438 r->path = (char *)(r+1);
443 last_path_rule = &r->next;
448 match_path_rule(struct path_rule *r, char *path)
452 if (*rr++ != *path++)
454 if (rr[-1] == '/' && !path[-1])
458 if (rr > r->path && rr[-1] != '/' && *path)
463 /*** Environment rules ***/
466 char *var; // Variable to match
467 char *val; // ""=clear, NULL=inherit
469 struct env_rule *next;
472 static struct env_rule *first_env_rule;
473 static struct env_rule **last_env_rule = &first_env_rule;
475 static struct env_rule default_env_rules[] = {
476 { "LIBC_FATAL_STDERR_", "1" }
480 set_env_action(char *a0)
482 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
483 char *a = (char *)(r+1);
486 char *sep = strchr(a, '=');
498 last_env_rule = &r->next;
504 match_env_var(char *env_entry, struct env_rule *r)
506 if (strncmp(env_entry, r->var, r->var_len))
508 return (env_entry[r->var_len] == '=');
512 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
514 // First remove the variable if already set
516 while (pos < *env_sizep && !match_env_var(env[pos], r))
518 if (pos < *env_sizep)
521 env[pos] = env[*env_sizep];
522 env[*env_sizep] = NULL;
525 // What is the new value?
531 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
532 sprintf(new, "%s=%s", r->var, r->val);
537 while (environ[pos] && !match_env_var(environ[pos], r))
539 if (!(new = environ[pos]))
543 // Add it at the end of the array
544 env[(*env_sizep)++] = new;
545 env[*env_sizep] = NULL;
549 setup_environment(void)
551 // Link built-in rules with user rules
552 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
554 default_env_rules[i].next = first_env_rule;
555 first_env_rule = &default_env_rules[i];
558 // Scan the original environment
559 char **orig_env = environ;
561 while (orig_env[orig_size])
564 // For each rule, reserve one more slot and calculate length
566 for (struct env_rule *r = first_env_rule; r; r=r->next)
569 r->var_len = strlen(r->var);
572 // Create a new environment
573 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
577 memcpy(env, environ, orig_size * sizeof(char *));
584 // Apply the rules one by one
585 for (struct env_rule *r = first_env_rule; r; r=r->next)
586 apply_env_rule(env, &size, r);
588 // Return the new env and pass some gossip
591 fprintf(stderr, "Passing environment:\n");
592 for (int i=0; env[i]; i++)
593 fprintf(stderr, "\t%s\n", env[i]);
598 /*** Low-level parsing of syscalls ***/
600 #ifdef CONFIG_BOX_AMD64
601 typedef uint64_t arg_t;
603 typedef uint32_t arg_t;
606 struct syscall_args {
608 arg_t arg1, arg2, arg3;
613 static int read_user_mem(arg_t addr, char *buf, int len)
620 sprintf(memname, "/proc/%d/mem", (int) box_pid);
621 mem_fd = open(memname, O_RDONLY);
623 die("open(%s): %m", memname);
625 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
626 die("lseek64(mem): %m");
627 return read(mem_fd, buf, len);
630 #ifdef CONFIG_BOX_AMD64
633 get_syscall_args(struct syscall_args *a, int is_exit)
635 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
636 die("ptrace(PTRACE_GETREGS): %m");
637 a->sys = a->user.regs.orig_rax;
638 a->arg1 = a->user.regs.rdi;
639 a->arg2 = a->user.regs.rsi;
640 a->arg3 = a->user.regs.rdx;
641 a->result = a->user.regs.rax;
644 * CAVEAT: We have to check carefully that this is a real 64-bit syscall.
645 * We test whether the process runs in 64-bit mode, but surprisingly this
646 * is not enough: a 64-bit process can still issue the INT 0x80 instruction
647 * which performs a 32-bit syscall. Currently, the only known way how to
648 * detect this situation is to inspect the instruction code (the kernel
649 * keeps a syscall type flag internally, but it is not accessible from
650 * user space). Hopefully, there is no instruction whose suffix is the
651 * code of the SYSCALL instruction. Sometimes, one would wish the
652 * instruction codes to be unique even when read backwards :)
658 switch (a->user.regs.cs)
661 err("FO: Forbidden 32-bit mode syscall");
665 err("XX: Unknown code segment %04jx", (intmax_t) a->user.regs.cs);
669 if (read_user_mem(a->user.regs.rip-2, (char *) &instr, 2) != 2)
670 err("FO: Cannot read syscall instruction");
676 err("FO: Forbidden 32-bit syscall in 64-bit mode");
678 err("FO: Unknown syscall instruction %04x", instr);
683 set_syscall_nr(struct syscall_args *a, arg_t sys)
686 a->user.regs.orig_rax = sys;
687 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
688 die("ptrace(PTRACE_SETREGS): %m");
694 get_syscall_args(struct syscall_args *a, int is_exit UNUSED)
696 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
697 die("ptrace(PTRACE_GETREGS): %m");
698 a->sys = a->user.regs.orig_eax;
699 a->arg1 = a->user.regs.ebx;
700 a->arg2 = a->user.regs.ecx;
701 a->arg3 = a->user.regs.edx;
702 a->result = a->user.regs.eax;
706 set_syscall_nr(struct syscall_args *a, arg_t sys)
709 a->user.regs.orig_eax = sys;
710 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
711 die("ptrace(PTRACE_SETREGS): %m");
716 /*** Syscall checks ***/
719 valid_filename(arg_t addr)
721 char namebuf[4096], *p, *end;
724 err("FA: File access forbidden");
725 if (file_access >= 9)
733 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
734 int l = namebuf + sizeof(namebuf) - end;
738 err("FA: Access to file with name too long");
739 remains = read_user_mem(addr, end, l);
741 die("read(mem): %m");
743 err("FA: Access to file with name out of memory");
750 msg("[%s] ", namebuf);
751 if (file_access >= 3)
754 // Everything in current directory is permitted
755 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
758 // ".." anywhere in the path is forbidden
759 enum action act = A_DEFAULT;
760 if (strstr(namebuf, ".."))
764 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
765 act = match_path_rule(r, namebuf);
767 // Scan built-in rules
768 if (file_access >= 2)
769 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
770 act = match_path_rule(&default_path_rules[i], namebuf);
773 err("FA: Forbidden access to file `%s'", namebuf);
776 // Check syscall. If invalid, return -1, otherwise return the action mask.
778 valid_syscall(struct syscall_args *a)
780 unsigned int sys = a->sys;
781 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
785 if (filter_syscalls != 1)
789 switch (act & A_ACTION_MASK)
796 valid_filename(a->arg1);
804 if (a->arg1 == (arg_t) box_pid)
806 meta_printf("exitsig:%d\n", (int) a->arg2);
807 err("SG: Committed suicide by signal %d", (int) a->arg2);
811 if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
813 meta_printf("exitsig:%d\n", (int) a->arg3);
814 err("SG: Committed suicide by signal %d", (int) a->arg3);
823 signal_alarm(int unused UNUSED)
825 /* Time limit checks are synchronous, so we only schedule them there. */
831 signal_int(int unused UNUSED)
833 /* Interrupts are fatal, so no synchronization requirements. */
834 meta_printf("exitsig:%d\n", SIGINT);
835 err("SG: Interrupted");
838 #define PROC_BUF_SIZE 4096
840 read_proc_file(char *buf, char *name, int *fdp)
846 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
847 *fdp = open(buf, O_RDONLY);
849 die("open(%s): %m", buf);
851 lseek(*fdp, 0, SEEK_SET);
852 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
853 die("read on /proc/$pid/%s: %m", name);
854 if (c >= PROC_BUF_SIZE-1)
855 die("/proc/$pid/%s too long", name);
864 struct timeval now, wall;
866 gettimeofday(&now, NULL);
867 timersub(&now, &start_time, &wall);
868 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
869 if (wall_ms > wall_timeout)
870 err("TO: Time limit exceeded (wall clock)");
872 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
876 char buf[PROC_BUF_SIZE], *x;
877 int utime, stime, ms;
878 static int proc_stat_fd;
879 read_proc_file(buf, "stat", &proc_stat_fd);
881 while (*x && *x != ' ')
886 die("proc stat syntax error 1");
887 while (*x && (*x != ')' || x[1] != ' '))
889 while (*x == ')' || *x == ' ')
891 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
892 die("proc stat syntax error 2");
893 ms = (utime + stime) * 1000 / ticks_per_sec;
895 fprintf(stderr, "[time check: %d msec]\n", ms);
896 if (ms > timeout && ms > extra_timeout)
897 err("TO: Time limit exceeded");
902 sample_mem_peak(void)
905 * We want to find out the peak memory usage of the process, which is
906 * maintained by the kernel, but unforunately it gets lost when the
907 * process exits (it is not reported in struct rusage). Therefore we
908 * have to sample it whenever we suspect that the process is about
911 char buf[PROC_BUF_SIZE], *x;
912 static int proc_status_fd;
913 read_proc_file(buf, "status", &proc_status_fd);
919 while (*x && *x != ':' && *x != '\n')
921 if (!*x || *x == '\n')
924 while (*x == ' ' || *x == '\t')
928 while (*x && *x != '\n')
934 if (!strcmp(key, "VmPeak"))
936 int peak = atoi(val);
937 if (peak > mem_peak_kb)
943 msg("[mem-peak: %u KB]\n", mem_peak_kb);
949 int syscall_count = (filter_syscalls ? 0 : 1);
954 bzero(&sa, sizeof(sa));
955 sa.sa_handler = signal_int;
956 sigaction(SIGINT, &sa, NULL);
958 gettimeofday(&start_time, NULL);
959 ticks_per_sec = sysconf(_SC_CLK_TCK);
960 if (ticks_per_sec <= 0)
961 die("Invalid ticks_per_sec!");
963 if (timeout || wall_timeout)
965 sa.sa_handler = signal_alarm;
966 sigaction(SIGALRM, &sa, NULL);
980 p = wait4(box_pid, &stat, WUNTRACED, &rus);
988 die("wait4: unknown pid %d exited!", p);
993 if (WEXITSTATUS(stat))
997 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
998 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1002 // Internal error happened inside the child process and it has been already reported.
1006 if (timeout && total_ms > timeout)
1007 err("TO: Time limit exceeded");
1008 if (wall_timeout && wall_ms > wall_timeout)
1009 err("TO: Time limit exceeded (wall clock)");
1011 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
1012 total_ms/1000, total_ms%1000,
1013 wall_ms/1000, wall_ms%1000,
1014 (mem_peak_kb + 1023) / 1024,
1018 if (WIFSIGNALED(stat))
1021 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1023 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
1025 if (WIFSTOPPED(stat))
1027 int sig = WSTOPSIG(stat);
1031 msg("[ptrace status %08x] ", stat);
1032 static int stop_count;
1033 if (!stop_count++) /* Traceme request */
1034 msg(">> Traceme request caught\n");
1036 err("SG: Breakpoint");
1037 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1039 else if (sig == (SIGTRAP | 0x80))
1042 msg("[ptrace status %08x] ", stat);
1043 struct syscall_args a;
1044 static unsigned int sys_tick, last_act;
1045 static arg_t last_sys;
1046 if (++sys_tick & 1) /* Syscall entry */
1051 get_syscall_args(&a, 0);
1053 msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1057 if (sys == __NR_execve)
1060 else if ((act = valid_syscall(&a)) >= 0)
1064 if (act & A_SAMPLE_MEM)
1070 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1071 * so we have to change it to something harmless (e.g., an undefined
1072 * syscall) and make the program continue.
1074 set_syscall_nr(&a, ~(arg_t)0);
1075 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1079 else /* Syscall return */
1081 get_syscall_args(&a, 1);
1082 if (a.sys == ~(arg_t)0)
1084 /* Some syscalls (sigreturn et al.) do not return a value */
1085 if (!(last_act & A_NO_RETVAL))
1086 err("XX: Syscall does not return, but it should");
1090 if (a.sys != last_sys)
1091 err("XX: Mismatched syscall entry/exit");
1093 if (last_act & A_NO_RETVAL)
1096 msg("= %jd\n", (intmax_t) a.result);
1098 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1100 else if (sig == SIGSTOP)
1102 msg(">> SIGSTOP\n");
1103 if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1104 die("ptrace(PTRACE_SETOPTIONS): %m");
1105 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1107 else if (sig != SIGXCPU && sig != SIGXFSZ)
1109 msg(">> Signal %d\n", sig);
1110 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
1111 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1115 meta_printf("exitsig:%d", sig);
1116 err("SG: Received signal %d", sig);
1120 die("wait4: unknown status %x, giving up!", stat);
1125 box_inside(int argc, char **argv)
1130 memcpy(args, argv, argc * sizeof(char *));
1132 if (set_cwd && chdir(set_cwd))
1137 if (open(redir_stdin, O_RDONLY) != 0)
1138 die("open(\"%s\"): %m", redir_stdin);
1143 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1144 die("open(\"%s\"): %m", redir_stdout);
1149 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1150 die("open(\"%s\"): %m", redir_stderr);
1158 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1159 if (setrlimit(RLIMIT_AS, &rl) < 0)
1160 die("setrlimit(RLIMIT_AS): %m");
1163 rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1164 if (setrlimit(RLIMIT_STACK, &rl) < 0)
1165 die("setrlimit(RLIMIT_STACK): %m");
1167 rl.rlim_cur = rl.rlim_max = 64;
1168 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1169 die("setrlimit(RLIMIT_NOFILE): %m");
1171 char **env = setup_environment();
1172 if (filter_syscalls)
1174 if (ptrace(PTRACE_TRACEME) < 0)
1175 die("ptrace(PTRACE_TRACEME): %m");
1176 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1179 execve(args[0], args, env);
1180 die("execve(\"%s\"): %m", args[0]);
1186 fprintf(stderr, "Invalid arguments!\n");
1188 Usage: box [<options>] -- <command> <arguments>\n\
1191 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1192 -c <dir>\tChange directory to <dir> first\n\
1193 -e\t\tInherit full environment of the parent process\n\
1194 -E <var>\tInherit the environment variable <var> from the parent process\n\
1195 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1196 -f\t\tFilter system calls (-ff=very restricted)\n\
1197 -i <file>\tRedirect stdin from <file>\n\
1198 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1199 -m <size>\tLimit address space to <size> KB\n\
1200 -M <file>\tOutput process information to <file> (name:value)\n\
1201 -o <file>\tRedirect stdout to <file>\n\
1202 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1203 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1204 -r <file>\tRedirect stderr to <file>\n\
1205 -s <sys>\tPermit the specified syscall (be careful)\n\
1206 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1207 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1208 -T\t\tAllow syscalls for measuring run time\n\
1209 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1210 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1211 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1212 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1218 main(int argc, char **argv)
1223 while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1227 file_access = atol(optarg);
1236 if (!set_env_action(optarg))
1243 stack_limit = atol(optarg);
1246 redir_stdin = optarg;
1249 memory_limit = atol(optarg);
1255 redir_stdout = optarg;
1258 if (!set_path_action(optarg))
1262 redir_stderr = optarg;
1265 if (!set_syscall_action(optarg))
1269 timeout = 1000*atof(optarg);
1272 syscall_action[__NR_times] = A_YES;
1278 wall_timeout = 1000*atof(optarg);
1281 extra_timeout = 1000*atof(optarg);
1290 if (setreuid(uid, uid) < 0)
1291 die("setreuid: %m");
1296 box_inside(argc-optind, argv+optind);
1299 die("Internal error: fell over edge of the world");