2 * A Simple Sandbox for Moe
4 * (c) 2001--2010 Martin Mares <mj@ucw.cz>
7 #define _LARGEFILE64_SOURCE
25 #include <sys/ptrace.h>
26 #include <sys/signal.h>
27 #include <sys/sysinfo.h>
28 #include <sys/resource.h>
29 #include <sys/utsname.h>
30 #include <linux/ptrace.h>
32 #if defined(CONFIG_BOX_KERNEL_AMD64) && !defined(CONFIG_BOX_USER_AMD64)
33 #include <asm/unistd_32.h>
34 #define NATIVE_NR_execve 59 /* 64-bit execve */
36 #include <asm/unistd.h>
37 #define NATIVE_NR_execve __NR_execve
40 #define NONRET __attribute__((noreturn))
41 #define UNUSED __attribute__((unused))
42 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
44 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
45 static int timeout; /* milliseconds */
46 static int wall_timeout;
47 static int extra_timeout;
48 static int pass_environ;
49 static int file_access;
51 static int memory_limit;
52 static int stack_limit;
53 static char *redir_stdin, *redir_stdout, *redir_stderr;
57 static int is_ptraced;
58 static volatile int timer_tick;
59 static struct timeval start_time;
60 static int ticks_per_sec;
62 static int partial_line;
64 static int mem_peak_kb;
65 static int total_ms, wall_ms;
67 static void die(char *msg, ...) NONRET;
68 static void sample_mem_peak(void);
72 static FILE *metafile;
75 meta_open(const char *name)
77 if (!strcmp(name, "-"))
82 metafile = fopen(name, "w");
84 die("Failed to open metafile '%s'",name);
90 if (metafile && metafile != stdout)
94 static void __attribute__((format(printf,1,2)))
95 meta_printf(const char *fmt, ...)
102 vfprintf(metafile, fmt, args);
107 final_stats(struct rusage *rus)
109 struct timeval total, now, wall;
110 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
111 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
112 gettimeofday(&now, NULL);
113 timersub(&now, &start_time, &wall);
114 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
116 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
117 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
118 meta_printf("mem:%llu\n", (unsigned long long) mem_peak_kb * 1024);
121 /*** Messages and exits ***/
130 ptrace(PTRACE_KILL, box_pid);
131 kill(-box_pid, SIGKILL);
132 kill(box_pid, SIGKILL);
133 meta_printf("killed:1\n");
138 p = wait4(box_pid, &stat, 0, &rus);
139 while (p < 0 && errno == EINTR);
141 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
157 /* Report an error of the sandbox itself */
158 static void NONRET __attribute__((format(printf,1,2)))
165 vsnprintf(buf, sizeof(buf), msg, args);
166 meta_printf("status:XX\nmessage:%s\n", buf);
172 /* Report an error of the program inside the sandbox */
173 static void NONRET __attribute__((format(printf,1,2)))
179 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
181 meta_printf("status:%c%c\n", msg[0], msg[1]);
185 vsnprintf(buf, sizeof(buf), msg, args);
186 meta_printf("message:%s\n", buf);
192 /* Write a message, but only if in verbose mode */
193 static void __attribute__((format(printf,1,2)))
200 int len = strlen(msg);
202 partial_line = (msg[len-1] != '\n');
203 vfprintf(stderr, msg, args);
212 void *p = malloc(size);
214 die("Out of memory");
218 /*** Syscall rules ***/
220 static const char * const syscall_names[] = {
221 #include "box/syscall-table.h"
223 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
224 #define NUM_ACTIONS (NUM_SYSCALLS+64)
227 A_DEFAULT, // Use the default action
228 A_NO, // Always forbid
229 A_YES, // Always permit
230 A_FILENAME, // Permit if arg1 is a known filename
232 A_NO_RETVAL = 32, // Does not return a value
233 A_SAMPLE_MEM = 64, // Sample memory usage before the syscall
234 A_LIBERAL = 128, // Valid only in liberal mode
235 // Must fit in a unsigned char
238 static unsigned char syscall_action[NUM_ACTIONS] = {
239 #define S(x) [__NR_##x]
241 // Syscalls permitted for specific file names
242 S(open) = A_FILENAME,
243 S(creat) = A_FILENAME,
244 S(unlink) = A_FILENAME,
245 S(access) = A_FILENAME,
246 S(truncate) = A_FILENAME,
247 S(stat) = A_FILENAME,
248 S(lstat) = A_FILENAME,
249 S(readlink) = A_FILENAME,
250 #ifndef CONFIG_BOX_USER_AMD64
251 S(oldstat) = A_FILENAME,
252 S(oldlstat) = A_FILENAME,
253 S(truncate64) = A_FILENAME,
254 S(stat64) = A_FILENAME,
255 S(lstat64) = A_FILENAME,
258 // Syscalls permitted always
259 S(exit) = A_YES | A_SAMPLE_MEM,
272 S(ftruncate) = A_YES,
274 S(personality) = A_YES,
277 S(getresuid) = A_YES,
291 S(set_thread_area) = A_YES,
292 S(get_thread_area) = A_YES,
293 S(set_tid_address) = A_YES,
294 S(exit_group) = A_YES | A_SAMPLE_MEM,
295 #ifdef CONFIG_BOX_USER_AMD64
296 S(arch_prctl) = A_YES,
299 S(ftruncate64) = A_YES,
306 // Syscalls permitted only in liberal mode
307 S(time) = A_YES | A_LIBERAL,
308 S(alarm) = A_YES | A_LIBERAL,
309 S(pause) = A_YES | A_LIBERAL,
310 S(fchmod) = A_YES | A_LIBERAL,
311 S(getrlimit) = A_YES | A_LIBERAL,
312 S(getrusage) = A_YES | A_LIBERAL,
313 S(gettimeofday) = A_YES | A_LIBERAL,
314 S(select) = A_YES | A_LIBERAL,
315 S(setitimer) = A_YES | A_LIBERAL,
316 S(getitimer) = A_YES | A_LIBERAL,
317 S(mprotect) = A_YES | A_LIBERAL,
318 S(getdents) = A_YES | A_LIBERAL,
319 S(getdents64) = A_YES | A_LIBERAL,
320 S(fdatasync) = A_YES | A_LIBERAL,
321 S(mremap) = A_YES | A_LIBERAL,
322 S(poll) = A_YES | A_LIBERAL,
323 S(getcwd) = A_YES | A_LIBERAL,
324 S(nanosleep) = A_YES | A_LIBERAL,
325 S(rt_sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
326 S(rt_sigaction) = A_YES | A_LIBERAL,
327 S(rt_sigprocmask) = A_YES | A_LIBERAL,
328 S(rt_sigpending) = A_YES | A_LIBERAL,
329 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
330 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
331 S(rt_sigsuspend) = A_YES | A_LIBERAL,
332 S(_sysctl) = A_YES | A_LIBERAL,
333 #ifndef CONFIG_BOX_USER_AMD64
334 S(sigaction) = A_YES | A_LIBERAL,
335 S(sgetmask) = A_YES | A_LIBERAL,
336 S(ssetmask) = A_YES | A_LIBERAL,
337 S(sigsuspend) = A_YES | A_LIBERAL,
338 S(sigpending) = A_YES | A_LIBERAL,
339 S(sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
340 S(sigprocmask) = A_YES | A_LIBERAL,
341 S(ugetrlimit) = A_YES | A_LIBERAL,
342 S(readdir) = A_YES | A_LIBERAL,
343 S(signal) = A_YES | A_LIBERAL,
344 S(_newselect) = A_YES | A_LIBERAL,
351 syscall_name(unsigned int id, char *buf)
353 if (id < NUM_SYSCALLS && syscall_names[id])
354 return syscall_names[id];
357 sprintf(buf, "#%d", id);
363 syscall_by_name(char *name)
365 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
366 if (syscall_names[i] && !strcmp(syscall_names[i], name))
373 unsigned long l = strtoul(name, &ep, 0);
376 if (l >= NUM_ACTIONS)
382 set_syscall_action(char *a)
384 char *sep = strchr(a, '=');
385 enum action act = A_YES;
389 if (!strcmp(sep, "yes"))
391 else if (!strcmp(sep, "no"))
393 else if (!strcmp(sep, "file"))
399 int sys = syscall_by_name(a);
401 die("Unknown syscall `%s'", a);
402 if (sys >= NUM_ACTIONS)
403 die("Syscall `%s' out of range", a);
404 syscall_action[sys] = act;
413 struct path_rule *next;
416 static struct path_rule default_path_rules[] = {
419 { "/usr/lib/", A_YES },
420 { "/opt/lib/", A_YES },
421 { "/usr/share/zoneinfo/", A_YES },
422 { "/usr/share/locale/", A_YES },
423 { "/dev/null", A_YES },
424 { "/dev/zero", A_YES },
425 { "/proc/meminfo", A_YES },
426 { "/proc/self/stat", A_YES },
427 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
428 { "/proc/self/maps", A_YES }, // Needed by glibc when it reports arena corruption
431 static struct path_rule *user_path_rules;
432 static struct path_rule **last_path_rule = &user_path_rules;
435 set_path_action(char *a)
437 char *sep = strchr(a, '=');
438 enum action act = A_YES;
442 if (!strcmp(sep, "yes"))
444 else if (!strcmp(sep, "no"))
450 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
451 r->path = (char *)(r+1);
456 last_path_rule = &r->next;
461 match_path_rule(struct path_rule *r, char *path)
465 if (*rr++ != *path++)
467 if (rr[-1] == '/' && !path[-1])
471 if (rr > r->path && rr[-1] != '/' && *path)
476 /*** Environment rules ***/
479 char *var; // Variable to match
480 char *val; // ""=clear, NULL=inherit
482 struct env_rule *next;
485 static struct env_rule *first_env_rule;
486 static struct env_rule **last_env_rule = &first_env_rule;
488 static struct env_rule default_env_rules[] = {
489 { "LIBC_FATAL_STDERR_", "1" }
493 set_env_action(char *a0)
495 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
496 char *a = (char *)(r+1);
499 char *sep = strchr(a, '=');
511 last_env_rule = &r->next;
517 match_env_var(char *env_entry, struct env_rule *r)
519 if (strncmp(env_entry, r->var, r->var_len))
521 return (env_entry[r->var_len] == '=');
525 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
527 // First remove the variable if already set
529 while (pos < *env_sizep && !match_env_var(env[pos], r))
531 if (pos < *env_sizep)
534 env[pos] = env[*env_sizep];
535 env[*env_sizep] = NULL;
538 // What is the new value?
544 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
545 sprintf(new, "%s=%s", r->var, r->val);
550 while (environ[pos] && !match_env_var(environ[pos], r))
552 if (!(new = environ[pos]))
556 // Add it at the end of the array
557 env[(*env_sizep)++] = new;
558 env[*env_sizep] = NULL;
562 setup_environment(void)
564 // Link built-in rules with user rules
565 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
567 default_env_rules[i].next = first_env_rule;
568 first_env_rule = &default_env_rules[i];
571 // Scan the original environment
572 char **orig_env = environ;
574 while (orig_env[orig_size])
577 // For each rule, reserve one more slot and calculate length
579 for (struct env_rule *r = first_env_rule; r; r=r->next)
582 r->var_len = strlen(r->var);
585 // Create a new environment
586 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
590 memcpy(env, environ, orig_size * sizeof(char *));
597 // Apply the rules one by one
598 for (struct env_rule *r = first_env_rule; r; r=r->next)
599 apply_env_rule(env, &size, r);
601 // Return the new env and pass some gossip
604 fprintf(stderr, "Passing environment:\n");
605 for (int i=0; env[i]; i++)
606 fprintf(stderr, "\t%s\n", env[i]);
611 /*** Low-level parsing of syscalls ***/
613 #ifdef CONFIG_BOX_KERNEL_AMD64
614 typedef uint64_t arg_t;
616 typedef uint32_t arg_t;
619 struct syscall_args {
621 arg_t arg1, arg2, arg3;
626 static int user_mem_fd;
628 static int read_user_mem(arg_t addr, char *buf, int len)
633 sprintf(memname, "/proc/%d/mem", (int) box_pid);
634 user_mem_fd = open(memname, O_RDONLY);
636 die("open(%s): %m", memname);
638 if (lseek64(user_mem_fd, addr, SEEK_SET) < 0)
639 die("lseek64(mem): %m");
640 return read(user_mem_fd, buf, len);
643 static void close_user_mem(void)
652 #ifdef CONFIG_BOX_KERNEL_AMD64
655 get_syscall_args(struct syscall_args *a, int is_exit)
657 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
658 die("ptrace(PTRACE_GETREGS): %m");
659 a->sys = a->user.regs.orig_rax;
660 a->result = a->user.regs.rax;
663 * CAVEAT: We have to check carefully that this is a real 64-bit syscall.
664 * We test whether the process runs in 64-bit mode, but surprisingly this
665 * is not enough: a 64-bit process can still issue the INT 0x80 instruction
666 * which performs a 32-bit syscall. Currently, the only known way how to
667 * detect this situation is to inspect the instruction code (the kernel
668 * keeps a syscall type flag internally, but it is not accessible from
669 * user space). Hopefully, there is no instruction whose suffix is the
670 * code of the SYSCALL instruction. Sometimes, one would wish the
671 * instruction codes to be unique even when read backwards :)
680 switch (a->user.regs.cs)
683 // 32-bit CPU mode => only 32-bit syscalls can be issued
688 if (read_user_mem(a->user.regs.rip-2, (char *) &instr, 2) != 2)
689 err("FO: Cannot read syscall instruction");
695 err("FO: Forbidden 32-bit syscall in 64-bit mode");
697 err("XX: Unknown syscall instruction %04x", instr);
702 err("XX: Unknown code segment %04jx", (intmax_t) a->user.regs.cs);
705 #ifdef CONFIG_BOX_USER_AMD64
707 err("FO: Forbidden %d-bit mode syscall", sys_type);
709 if (sys_type != (exec_seen ? 32 : 64))
710 err("FO: Forbidden %d-bit mode syscall", sys_type);
715 a->arg1 = a->user.regs.rbx;
716 a->arg2 = a->user.regs.rcx;
717 a->arg3 = a->user.regs.rdx;
721 a->arg1 = a->user.regs.rdi;
722 a->arg2 = a->user.regs.rsi;
723 a->arg3 = a->user.regs.rdx;
728 set_syscall_nr(struct syscall_args *a, arg_t sys)
731 a->user.regs.orig_rax = sys;
732 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
733 die("ptrace(PTRACE_SETREGS): %m");
744 get_syscall_args(struct syscall_args *a, int is_exit UNUSED)
746 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
747 die("ptrace(PTRACE_GETREGS): %m");
748 a->sys = a->user.regs.orig_eax;
749 a->arg1 = a->user.regs.ebx;
750 a->arg2 = a->user.regs.ecx;
751 a->arg3 = a->user.regs.edx;
752 a->result = a->user.regs.eax;
756 set_syscall_nr(struct syscall_args *a, arg_t sys)
759 a->user.regs.orig_eax = sys;
760 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
761 die("ptrace(PTRACE_SETREGS): %m");
767 #if !defined(CONFIG_BOX_ALLOW_INSECURE)
770 die("uname() failed: %m");
772 if (!strcmp(uts.machine, "x86_64"))
773 die("Running 32-bit sandbox on 64-bit kernels is inherently unsafe. Please get a 64-bit version.");
779 /*** Syscall checks ***/
782 valid_filename(arg_t addr)
784 char namebuf[4096], *p, *end;
787 err("FA: File access forbidden");
788 if (file_access >= 9)
796 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
797 int l = namebuf + sizeof(namebuf) - end;
801 err("FA: Access to file with name too long");
802 remains = read_user_mem(addr, end, l);
804 die("read(mem): %m");
806 err("FA: Access to file with name out of memory");
813 msg("[%s] ", namebuf);
814 if (file_access >= 3)
817 // Everything in current directory is permitted
818 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
821 // ".." anywhere in the path is forbidden
822 enum action act = A_DEFAULT;
823 if (strstr(namebuf, ".."))
827 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
828 act = match_path_rule(r, namebuf);
830 // Scan built-in rules
831 if (file_access >= 2)
832 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
833 act = match_path_rule(&default_path_rules[i], namebuf);
836 err("FA: Forbidden access to file `%s'", namebuf);
839 // Check syscall. If invalid, return -1, otherwise return the action mask.
841 valid_syscall(struct syscall_args *a)
843 unsigned int sys = a->sys;
844 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
848 if (filter_syscalls != 1)
852 switch (act & A_ACTION_MASK)
859 valid_filename(a->arg1);
867 if (a->arg1 == (arg_t) box_pid)
869 meta_printf("exitsig:%d\n", (int) a->arg2);
870 err("SG: Committed suicide by signal %d", (int) a->arg2);
874 if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
876 meta_printf("exitsig:%d\n", (int) a->arg3);
877 err("SG: Committed suicide by signal %d", (int) a->arg3);
886 signal_alarm(int unused UNUSED)
888 /* Time limit checks are synchronous, so we only schedule them there. */
894 signal_int(int unused UNUSED)
896 /* Interrupts are fatal, so no synchronization requirements. */
897 meta_printf("exitsig:%d\n", SIGINT);
898 err("SG: Interrupted");
901 #define PROC_BUF_SIZE 4096
903 read_proc_file(char *buf, char *name, int *fdp)
909 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
910 *fdp = open(buf, O_RDONLY);
912 die("open(%s): %m", buf);
914 lseek(*fdp, 0, SEEK_SET);
915 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
916 die("read on /proc/$pid/%s: %m", name);
917 if (c >= PROC_BUF_SIZE-1)
918 die("/proc/$pid/%s too long", name);
927 struct timeval now, wall;
929 gettimeofday(&now, NULL);
930 timersub(&now, &start_time, &wall);
931 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
932 if (wall_ms > wall_timeout)
933 err("TO: Time limit exceeded (wall clock)");
935 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
939 char buf[PROC_BUF_SIZE], *x;
940 int utime, stime, ms;
941 static int proc_stat_fd;
942 read_proc_file(buf, "stat", &proc_stat_fd);
944 while (*x && *x != ' ')
949 die("proc stat syntax error 1");
950 while (*x && (*x != ')' || x[1] != ' '))
952 while (*x == ')' || *x == ' ')
954 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
955 die("proc stat syntax error 2");
956 ms = (utime + stime) * 1000 / ticks_per_sec;
958 fprintf(stderr, "[time check: %d msec]\n", ms);
959 if (ms > timeout && ms > extra_timeout)
960 err("TO: Time limit exceeded");
965 sample_mem_peak(void)
968 * We want to find out the peak memory usage of the process, which is
969 * maintained by the kernel, but unforunately it gets lost when the
970 * process exits (it is not reported in struct rusage). Therefore we
971 * have to sample it whenever we suspect that the process is about
974 char buf[PROC_BUF_SIZE], *x;
975 static int proc_status_fd;
976 read_proc_file(buf, "status", &proc_status_fd);
982 while (*x && *x != ':' && *x != '\n')
984 if (!*x || *x == '\n')
987 while (*x == ' ' || *x == '\t')
991 while (*x && *x != '\n')
997 if (!strcmp(key, "VmPeak"))
999 int peak = atoi(val);
1000 if (peak > mem_peak_kb)
1006 msg("[mem-peak: %u KB]\n", mem_peak_kb);
1012 int syscall_count = (filter_syscalls ? 0 : 1);
1013 struct sigaction sa;
1017 bzero(&sa, sizeof(sa));
1018 sa.sa_handler = signal_int;
1019 sigaction(SIGINT, &sa, NULL);
1021 gettimeofday(&start_time, NULL);
1022 ticks_per_sec = sysconf(_SC_CLK_TCK);
1023 if (ticks_per_sec <= 0)
1024 die("Invalid ticks_per_sec!");
1026 if (timeout || wall_timeout)
1028 sa.sa_handler = signal_alarm;
1029 sigaction(SIGALRM, &sa, NULL);
1043 p = wait4(box_pid, &stat, WUNTRACED, &rus);
1051 die("wait4: unknown pid %d exited!", p);
1052 if (WIFEXITED(stat))
1056 if (WEXITSTATUS(stat))
1060 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1061 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1065 // Internal error happened inside the child process and it has been already reported.
1069 if (timeout && total_ms > timeout)
1070 err("TO: Time limit exceeded");
1071 if (wall_timeout && wall_ms > wall_timeout)
1072 err("TO: Time limit exceeded (wall clock)");
1074 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
1075 total_ms/1000, total_ms%1000,
1076 wall_ms/1000, wall_ms%1000,
1077 (mem_peak_kb + 1023) / 1024,
1081 if (WIFSIGNALED(stat))
1084 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1086 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
1088 if (WIFSTOPPED(stat))
1090 int sig = WSTOPSIG(stat);
1094 msg("[ptrace status %08x] ", stat);
1095 static int stop_count;
1096 if (!stop_count++) /* Traceme request */
1097 msg(">> Traceme request caught\n");
1099 err("SG: Breakpoint");
1100 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1102 else if (sig == (SIGTRAP | 0x80))
1105 msg("[ptrace status %08x] ", stat);
1106 struct syscall_args a;
1107 static unsigned int sys_tick, last_act;
1108 static arg_t last_sys;
1109 if (++sys_tick & 1) /* Syscall entry */
1114 get_syscall_args(&a, 0);
1116 msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1120 if (sys == NATIVE_NR_execve)
1126 else if ((act = valid_syscall(&a)) >= 0)
1130 if (act & A_SAMPLE_MEM)
1136 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1137 * so we have to change it to something harmless (e.g., an undefined
1138 * syscall) and make the program continue.
1140 set_syscall_nr(&a, ~(arg_t)0);
1141 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1145 else /* Syscall return */
1147 get_syscall_args(&a, 1);
1148 if (a.sys == ~(arg_t)0)
1150 /* Some syscalls (sigreturn et al.) do not return a value */
1151 if (!(last_act & A_NO_RETVAL))
1152 err("XX: Syscall does not return, but it should");
1156 if (a.sys != last_sys)
1157 err("XX: Mismatched syscall entry/exit");
1159 if (last_act & A_NO_RETVAL)
1162 msg("= %jd\n", (intmax_t) a.result);
1164 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1166 else if (sig == SIGSTOP)
1168 msg(">> SIGSTOP\n");
1169 if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1170 die("ptrace(PTRACE_SETOPTIONS): %m");
1171 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1173 else if (sig != SIGXCPU && sig != SIGXFSZ)
1175 msg(">> Signal %d\n", sig);
1176 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
1177 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1181 meta_printf("exitsig:%d", sig);
1182 err("SG: Received signal %d", sig);
1186 die("wait4: unknown status %x, giving up!", stat);
1191 box_inside(int argc, char **argv)
1196 memcpy(args, argv, argc * sizeof(char *));
1198 if (set_cwd && chdir(set_cwd))
1203 if (open(redir_stdin, O_RDONLY) != 0)
1204 die("open(\"%s\"): %m", redir_stdin);
1209 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1210 die("open(\"%s\"): %m", redir_stdout);
1215 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1216 die("open(\"%s\"): %m", redir_stderr);
1224 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1225 if (setrlimit(RLIMIT_AS, &rl) < 0)
1226 die("setrlimit(RLIMIT_AS): %m");
1229 rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1230 if (setrlimit(RLIMIT_STACK, &rl) < 0)
1231 die("setrlimit(RLIMIT_STACK): %m");
1233 rl.rlim_cur = rl.rlim_max = 64;
1234 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1235 die("setrlimit(RLIMIT_NOFILE): %m");
1237 char **env = setup_environment();
1238 if (filter_syscalls)
1240 if (ptrace(PTRACE_TRACEME) < 0)
1241 die("ptrace(PTRACE_TRACEME): %m");
1242 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1245 execve(args[0], args, env);
1246 die("execve(\"%s\"): %m", args[0]);
1252 fprintf(stderr, "Invalid arguments!\n");
1254 Usage: box [<options>] -- <command> <arguments>\n\
1257 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1258 -c <dir>\tChange directory to <dir> first\n\
1259 -e\t\tInherit full environment of the parent process\n\
1260 -E <var>\tInherit the environment variable <var> from the parent process\n\
1261 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1262 -f\t\tFilter system calls (-ff=very restricted)\n\
1263 -i <file>\tRedirect stdin from <file>\n\
1264 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1265 -m <size>\tLimit address space to <size> KB\n\
1266 -M <file>\tOutput process information to <file> (name:value)\n\
1267 -o <file>\tRedirect stdout to <file>\n\
1268 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1269 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1270 -r <file>\tRedirect stderr to <file>\n\
1271 -s <sys>\tPermit the specified syscall (be careful)\n\
1272 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1273 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1274 -T\t\tAllow syscalls for measuring run time\n\
1275 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1276 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1277 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1278 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1284 main(int argc, char **argv)
1289 while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1293 file_access = atol(optarg);
1302 if (!set_env_action(optarg))
1309 stack_limit = atol(optarg);
1312 redir_stdin = optarg;
1315 memory_limit = atol(optarg);
1321 redir_stdout = optarg;
1324 if (!set_path_action(optarg))
1328 redir_stderr = optarg;
1331 if (!set_syscall_action(optarg))
1335 timeout = 1000*atof(optarg);
1338 syscall_action[__NR_times] = A_YES;
1344 wall_timeout = 1000*atof(optarg);
1347 extra_timeout = 1000*atof(optarg);
1357 if (setreuid(uid, uid) < 0)
1358 die("setreuid: %m");
1363 box_inside(argc-optind, argv+optind);
1366 die("Internal error: fell over edge of the world");