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
430 static struct path_rule *user_path_rules;
431 static struct path_rule **last_path_rule = &user_path_rules;
434 set_path_action(char *a)
436 char *sep = strchr(a, '=');
437 enum action act = A_YES;
441 if (!strcmp(sep, "yes"))
443 else if (!strcmp(sep, "no"))
449 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
450 r->path = (char *)(r+1);
455 last_path_rule = &r->next;
460 match_path_rule(struct path_rule *r, char *path)
464 if (*rr++ != *path++)
466 if (rr[-1] == '/' && !path[-1])
470 if (rr > r->path && rr[-1] != '/' && *path)
475 /*** Environment rules ***/
478 char *var; // Variable to match
479 char *val; // ""=clear, NULL=inherit
481 struct env_rule *next;
484 static struct env_rule *first_env_rule;
485 static struct env_rule **last_env_rule = &first_env_rule;
487 static struct env_rule default_env_rules[] = {
488 { "LIBC_FATAL_STDERR_", "1" }
492 set_env_action(char *a0)
494 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
495 char *a = (char *)(r+1);
498 char *sep = strchr(a, '=');
510 last_env_rule = &r->next;
516 match_env_var(char *env_entry, struct env_rule *r)
518 if (strncmp(env_entry, r->var, r->var_len))
520 return (env_entry[r->var_len] == '=');
524 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
526 // First remove the variable if already set
528 while (pos < *env_sizep && !match_env_var(env[pos], r))
530 if (pos < *env_sizep)
533 env[pos] = env[*env_sizep];
534 env[*env_sizep] = NULL;
537 // What is the new value?
543 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
544 sprintf(new, "%s=%s", r->var, r->val);
549 while (environ[pos] && !match_env_var(environ[pos], r))
551 if (!(new = environ[pos]))
555 // Add it at the end of the array
556 env[(*env_sizep)++] = new;
557 env[*env_sizep] = NULL;
561 setup_environment(void)
563 // Link built-in rules with user rules
564 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
566 default_env_rules[i].next = first_env_rule;
567 first_env_rule = &default_env_rules[i];
570 // Scan the original environment
571 char **orig_env = environ;
573 while (orig_env[orig_size])
576 // For each rule, reserve one more slot and calculate length
578 for (struct env_rule *r = first_env_rule; r; r=r->next)
581 r->var_len = strlen(r->var);
584 // Create a new environment
585 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
589 memcpy(env, environ, orig_size * sizeof(char *));
596 // Apply the rules one by one
597 for (struct env_rule *r = first_env_rule; r; r=r->next)
598 apply_env_rule(env, &size, r);
600 // Return the new env and pass some gossip
603 fprintf(stderr, "Passing environment:\n");
604 for (int i=0; env[i]; i++)
605 fprintf(stderr, "\t%s\n", env[i]);
610 /*** Low-level parsing of syscalls ***/
612 #ifdef CONFIG_BOX_KERNEL_AMD64
613 typedef uint64_t arg_t;
615 typedef uint32_t arg_t;
618 struct syscall_args {
620 arg_t arg1, arg2, arg3;
625 static int read_user_mem(arg_t addr, char *buf, int len)
632 sprintf(memname, "/proc/%d/mem", (int) box_pid);
633 mem_fd = open(memname, O_RDONLY);
635 die("open(%s): %m", memname);
637 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
638 die("lseek64(mem): %m");
639 return read(mem_fd, buf, len);
642 #ifdef CONFIG_BOX_KERNEL_AMD64
645 get_syscall_args(struct syscall_args *a, int is_exit)
647 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
648 die("ptrace(PTRACE_GETREGS): %m");
649 a->sys = a->user.regs.orig_rax;
650 a->result = a->user.regs.rax;
653 * CAVEAT: We have to check carefully that this is a real 64-bit syscall.
654 * We test whether the process runs in 64-bit mode, but surprisingly this
655 * is not enough: a 64-bit process can still issue the INT 0x80 instruction
656 * which performs a 32-bit syscall. Currently, the only known way how to
657 * detect this situation is to inspect the instruction code (the kernel
658 * keeps a syscall type flag internally, but it is not accessible from
659 * user space). Hopefully, there is no instruction whose suffix is the
660 * code of the SYSCALL instruction. Sometimes, one would wish the
661 * instruction codes to be unique even when read backwards :)
670 switch (a->user.regs.cs)
673 // 32-bit CPU mode => only 32-bit syscalls can be issued
678 if (read_user_mem(a->user.regs.rip-2, (char *) &instr, 2) != 2)
679 err("FO: Cannot read syscall instruction");
685 err("FO: Forbidden 32-bit syscall in 64-bit mode");
687 err("XX: Unknown syscall instruction %04x", instr);
692 err("XX: Unknown code segment %04jx", (intmax_t) a->user.regs.cs);
695 #ifdef CONFIG_BOX_USER_AMD64
697 err("FO: Forbidden %d-bit mode syscall", sys_type);
699 if (sys_type != (exec_seen ? 32 : 64))
700 err("FO: Forbidden %d-bit mode syscall", sys_type);
705 a->arg1 = a->user.regs.rbx;
706 a->arg2 = a->user.regs.rcx;
707 a->arg3 = a->user.regs.rdx;
711 a->arg1 = a->user.regs.rdi;
712 a->arg2 = a->user.regs.rsi;
713 a->arg3 = a->user.regs.rdx;
718 set_syscall_nr(struct syscall_args *a, arg_t sys)
721 a->user.regs.orig_rax = sys;
722 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
723 die("ptrace(PTRACE_SETREGS): %m");
734 get_syscall_args(struct syscall_args *a, int is_exit UNUSED)
736 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
737 die("ptrace(PTRACE_GETREGS): %m");
738 a->sys = a->user.regs.orig_eax;
739 a->arg1 = a->user.regs.ebx;
740 a->arg2 = a->user.regs.ecx;
741 a->arg3 = a->user.regs.edx;
742 a->result = a->user.regs.eax;
746 set_syscall_nr(struct syscall_args *a, arg_t sys)
749 a->user.regs.orig_eax = sys;
750 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
751 die("ptrace(PTRACE_SETREGS): %m");
757 #if !defined(CONFIG_BOX_ALLOW_INSECURE)
760 die("uname() failed: %m");
762 if (!strcmp(uts.machine, "x86_64"))
763 die("Running 32-bit sandbox on 64-bit kernels is inherently unsafe. Please get a 64-bit version.");
769 /*** Syscall checks ***/
772 valid_filename(arg_t addr)
774 char namebuf[4096], *p, *end;
777 err("FA: File access forbidden");
778 if (file_access >= 9)
786 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
787 int l = namebuf + sizeof(namebuf) - end;
791 err("FA: Access to file with name too long");
792 remains = read_user_mem(addr, end, l);
794 die("read(mem): %m");
796 err("FA: Access to file with name out of memory");
803 msg("[%s] ", namebuf);
804 if (file_access >= 3)
807 // Everything in current directory is permitted
808 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
811 // ".." anywhere in the path is forbidden
812 enum action act = A_DEFAULT;
813 if (strstr(namebuf, ".."))
817 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
818 act = match_path_rule(r, namebuf);
820 // Scan built-in rules
821 if (file_access >= 2)
822 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
823 act = match_path_rule(&default_path_rules[i], namebuf);
826 err("FA: Forbidden access to file `%s'", namebuf);
829 // Check syscall. If invalid, return -1, otherwise return the action mask.
831 valid_syscall(struct syscall_args *a)
833 unsigned int sys = a->sys;
834 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
838 if (filter_syscalls != 1)
842 switch (act & A_ACTION_MASK)
849 valid_filename(a->arg1);
857 if (a->arg1 == (arg_t) box_pid)
859 meta_printf("exitsig:%d\n", (int) a->arg2);
860 err("SG: Committed suicide by signal %d", (int) a->arg2);
864 if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
866 meta_printf("exitsig:%d\n", (int) a->arg3);
867 err("SG: Committed suicide by signal %d", (int) a->arg3);
876 signal_alarm(int unused UNUSED)
878 /* Time limit checks are synchronous, so we only schedule them there. */
884 signal_int(int unused UNUSED)
886 /* Interrupts are fatal, so no synchronization requirements. */
887 meta_printf("exitsig:%d\n", SIGINT);
888 err("SG: Interrupted");
891 #define PROC_BUF_SIZE 4096
893 read_proc_file(char *buf, char *name, int *fdp)
899 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
900 *fdp = open(buf, O_RDONLY);
902 die("open(%s): %m", buf);
904 lseek(*fdp, 0, SEEK_SET);
905 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
906 die("read on /proc/$pid/%s: %m", name);
907 if (c >= PROC_BUF_SIZE-1)
908 die("/proc/$pid/%s too long", name);
917 struct timeval now, wall;
919 gettimeofday(&now, NULL);
920 timersub(&now, &start_time, &wall);
921 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
922 if (wall_ms > wall_timeout)
923 err("TO: Time limit exceeded (wall clock)");
925 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
929 char buf[PROC_BUF_SIZE], *x;
930 int utime, stime, ms;
931 static int proc_stat_fd;
932 read_proc_file(buf, "stat", &proc_stat_fd);
934 while (*x && *x != ' ')
939 die("proc stat syntax error 1");
940 while (*x && (*x != ')' || x[1] != ' '))
942 while (*x == ')' || *x == ' ')
944 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
945 die("proc stat syntax error 2");
946 ms = (utime + stime) * 1000 / ticks_per_sec;
948 fprintf(stderr, "[time check: %d msec]\n", ms);
949 if (ms > timeout && ms > extra_timeout)
950 err("TO: Time limit exceeded");
955 sample_mem_peak(void)
958 * We want to find out the peak memory usage of the process, which is
959 * maintained by the kernel, but unforunately it gets lost when the
960 * process exits (it is not reported in struct rusage). Therefore we
961 * have to sample it whenever we suspect that the process is about
964 char buf[PROC_BUF_SIZE], *x;
965 static int proc_status_fd;
966 read_proc_file(buf, "status", &proc_status_fd);
972 while (*x && *x != ':' && *x != '\n')
974 if (!*x || *x == '\n')
977 while (*x == ' ' || *x == '\t')
981 while (*x && *x != '\n')
987 if (!strcmp(key, "VmPeak"))
989 int peak = atoi(val);
990 if (peak > mem_peak_kb)
996 msg("[mem-peak: %u KB]\n", mem_peak_kb);
1002 int syscall_count = (filter_syscalls ? 0 : 1);
1003 struct sigaction sa;
1007 bzero(&sa, sizeof(sa));
1008 sa.sa_handler = signal_int;
1009 sigaction(SIGINT, &sa, NULL);
1011 gettimeofday(&start_time, NULL);
1012 ticks_per_sec = sysconf(_SC_CLK_TCK);
1013 if (ticks_per_sec <= 0)
1014 die("Invalid ticks_per_sec!");
1016 if (timeout || wall_timeout)
1018 sa.sa_handler = signal_alarm;
1019 sigaction(SIGALRM, &sa, NULL);
1033 p = wait4(box_pid, &stat, WUNTRACED, &rus);
1041 die("wait4: unknown pid %d exited!", p);
1042 if (WIFEXITED(stat))
1046 if (WEXITSTATUS(stat))
1050 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1051 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1055 // Internal error happened inside the child process and it has been already reported.
1059 if (timeout && total_ms > timeout)
1060 err("TO: Time limit exceeded");
1061 if (wall_timeout && wall_ms > wall_timeout)
1062 err("TO: Time limit exceeded (wall clock)");
1064 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
1065 total_ms/1000, total_ms%1000,
1066 wall_ms/1000, wall_ms%1000,
1067 (mem_peak_kb + 1023) / 1024,
1071 if (WIFSIGNALED(stat))
1074 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1076 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
1078 if (WIFSTOPPED(stat))
1080 int sig = WSTOPSIG(stat);
1084 msg("[ptrace status %08x] ", stat);
1085 static int stop_count;
1086 if (!stop_count++) /* Traceme request */
1087 msg(">> Traceme request caught\n");
1089 err("SG: Breakpoint");
1090 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1092 else if (sig == (SIGTRAP | 0x80))
1095 msg("[ptrace status %08x] ", stat);
1096 struct syscall_args a;
1097 static unsigned int sys_tick, last_act;
1098 static arg_t last_sys;
1099 if (++sys_tick & 1) /* Syscall entry */
1104 get_syscall_args(&a, 0);
1106 msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1110 if (sys == NATIVE_NR_execve)
1113 else if ((act = valid_syscall(&a)) >= 0)
1117 if (act & A_SAMPLE_MEM)
1123 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1124 * so we have to change it to something harmless (e.g., an undefined
1125 * syscall) and make the program continue.
1127 set_syscall_nr(&a, ~(arg_t)0);
1128 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1132 else /* Syscall return */
1134 get_syscall_args(&a, 1);
1135 if (a.sys == ~(arg_t)0)
1137 /* Some syscalls (sigreturn et al.) do not return a value */
1138 if (!(last_act & A_NO_RETVAL))
1139 err("XX: Syscall does not return, but it should");
1143 if (a.sys != last_sys)
1144 err("XX: Mismatched syscall entry/exit");
1146 if (last_act & A_NO_RETVAL)
1149 msg("= %jd\n", (intmax_t) a.result);
1151 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1153 else if (sig == SIGSTOP)
1155 msg(">> SIGSTOP\n");
1156 if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1157 die("ptrace(PTRACE_SETOPTIONS): %m");
1158 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1160 else if (sig != SIGXCPU && sig != SIGXFSZ)
1162 msg(">> Signal %d\n", sig);
1163 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
1164 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1168 meta_printf("exitsig:%d", sig);
1169 err("SG: Received signal %d", sig);
1173 die("wait4: unknown status %x, giving up!", stat);
1178 box_inside(int argc, char **argv)
1183 memcpy(args, argv, argc * sizeof(char *));
1185 if (set_cwd && chdir(set_cwd))
1190 if (open(redir_stdin, O_RDONLY) != 0)
1191 die("open(\"%s\"): %m", redir_stdin);
1196 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1197 die("open(\"%s\"): %m", redir_stdout);
1202 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1203 die("open(\"%s\"): %m", redir_stderr);
1211 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1212 if (setrlimit(RLIMIT_AS, &rl) < 0)
1213 die("setrlimit(RLIMIT_AS): %m");
1216 rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1217 if (setrlimit(RLIMIT_STACK, &rl) < 0)
1218 die("setrlimit(RLIMIT_STACK): %m");
1220 rl.rlim_cur = rl.rlim_max = 64;
1221 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1222 die("setrlimit(RLIMIT_NOFILE): %m");
1224 char **env = setup_environment();
1225 if (filter_syscalls)
1227 if (ptrace(PTRACE_TRACEME) < 0)
1228 die("ptrace(PTRACE_TRACEME): %m");
1229 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1232 execve(args[0], args, env);
1233 die("execve(\"%s\"): %m", args[0]);
1239 fprintf(stderr, "Invalid arguments!\n");
1241 Usage: box [<options>] -- <command> <arguments>\n\
1244 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1245 -c <dir>\tChange directory to <dir> first\n\
1246 -e\t\tInherit full environment of the parent process\n\
1247 -E <var>\tInherit the environment variable <var> from the parent process\n\
1248 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1249 -f\t\tFilter system calls (-ff=very restricted)\n\
1250 -i <file>\tRedirect stdin from <file>\n\
1251 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1252 -m <size>\tLimit address space to <size> KB\n\
1253 -M <file>\tOutput process information to <file> (name:value)\n\
1254 -o <file>\tRedirect stdout to <file>\n\
1255 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1256 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1257 -r <file>\tRedirect stderr to <file>\n\
1258 -s <sys>\tPermit the specified syscall (be careful)\n\
1259 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1260 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1261 -T\t\tAllow syscalls for measuring run time\n\
1262 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1263 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1264 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1265 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1271 main(int argc, char **argv)
1276 while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1280 file_access = atol(optarg);
1289 if (!set_env_action(optarg))
1296 stack_limit = atol(optarg);
1299 redir_stdin = optarg;
1302 memory_limit = atol(optarg);
1308 redir_stdout = optarg;
1311 if (!set_path_action(optarg))
1315 redir_stderr = optarg;
1318 if (!set_syscall_action(optarg))
1322 timeout = 1000*atof(optarg);
1325 syscall_action[__NR_times] = A_YES;
1331 wall_timeout = 1000*atof(optarg);
1334 extra_timeout = 1000*atof(optarg);
1344 if (setreuid(uid, uid) < 0)
1345 die("setreuid: %m");
1350 box_inside(argc-optind, argv+optind);
1353 die("Internal error: fell over edge of the world");