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/resource.h>
27 #include <linux/ptrace.h>
29 #if defined(CONFIG_BOX_KERNEL_AMD64) && !defined(CONFIG_BOX_USER_AMD64)
30 #include <asm/unistd_32.h>
31 #define NATIVE_NR_execve 59 /* 64-bit execve */
33 #include <asm/unistd.h>
34 #define NATIVE_NR_execve __NR_execve
37 #define NONRET __attribute__((noreturn))
38 #define UNUSED __attribute__((unused))
39 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
41 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
42 static int timeout; /* milliseconds */
43 static int wall_timeout;
44 static int extra_timeout;
45 static int pass_environ;
46 static int file_access;
48 static int memory_limit;
49 static int stack_limit;
50 static char *redir_stdin, *redir_stdout, *redir_stderr;
54 static int is_ptraced;
55 static volatile int timer_tick;
56 static struct timeval start_time;
57 static int ticks_per_sec;
59 static int partial_line;
61 static int mem_peak_kb;
62 static int total_ms, wall_ms;
64 static void die(char *msg, ...) NONRET;
65 static void sample_mem_peak(void);
69 static FILE *metafile;
72 meta_open(const char *name)
74 if (!strcmp(name, "-"))
79 metafile = fopen(name, "w");
81 die("Failed to open metafile '%s'",name);
87 if (metafile && metafile != stdout)
91 static void __attribute__((format(printf,1,2)))
92 meta_printf(const char *fmt, ...)
99 vfprintf(metafile, fmt, args);
104 final_stats(struct rusage *rus)
106 struct timeval total, now, wall;
107 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
108 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
109 gettimeofday(&now, NULL);
110 timersub(&now, &start_time, &wall);
111 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
113 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
114 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
115 meta_printf("mem:%llu\n", (unsigned long long) mem_peak_kb * 1024);
118 /*** Messages and exits ***/
127 ptrace(PTRACE_KILL, box_pid);
128 kill(-box_pid, SIGKILL);
129 kill(box_pid, SIGKILL);
130 meta_printf("killed:1\n");
135 p = wait4(box_pid, &stat, 0, &rus);
136 while (p < 0 && errno == EINTR);
138 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
154 /* Report an error of the sandbox itself */
155 static void NONRET __attribute__((format(printf,1,2)))
162 vsnprintf(buf, sizeof(buf), msg, args);
163 meta_printf("status:XX\nmessage:%s\n", buf);
169 /* Report an error of the program inside the sandbox */
170 static void NONRET __attribute__((format(printf,1,2)))
176 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
178 meta_printf("status:%c%c\n", msg[0], msg[1]);
182 vsnprintf(buf, sizeof(buf), msg, args);
183 meta_printf("message:%s\n", buf);
189 /* Write a message, but only if in verbose mode */
190 static void __attribute__((format(printf,1,2)))
197 int len = strlen(msg);
199 partial_line = (msg[len-1] != '\n');
200 vfprintf(stderr, msg, args);
209 void *p = malloc(size);
211 die("Out of memory");
215 /*** Syscall rules ***/
217 static const char * const syscall_names[] = {
218 #include "box/syscall-table.h"
220 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
221 #define NUM_ACTIONS (NUM_SYSCALLS+64)
224 A_DEFAULT, // Use the default action
225 A_NO, // Always forbid
226 A_YES, // Always permit
227 A_FILENAME, // Permit if arg1 is a known filename
229 A_NO_RETVAL = 32, // Does not return a value
230 A_SAMPLE_MEM = 64, // Sample memory usage before the syscall
231 A_LIBERAL = 128, // Valid only in liberal mode
232 // Must fit in a unsigned char
235 static unsigned char syscall_action[NUM_ACTIONS] = {
236 #define S(x) [__NR_##x]
238 // Syscalls permitted for specific file names
239 S(open) = A_FILENAME,
240 S(creat) = A_FILENAME,
241 S(unlink) = A_FILENAME,
242 S(access) = A_FILENAME,
243 S(truncate) = A_FILENAME,
244 S(stat) = A_FILENAME,
245 S(lstat) = A_FILENAME,
246 S(readlink) = A_FILENAME,
247 #ifndef CONFIG_BOX_USER_AMD64
248 S(oldstat) = A_FILENAME,
249 S(oldlstat) = A_FILENAME,
250 S(truncate64) = A_FILENAME,
251 S(stat64) = A_FILENAME,
252 S(lstat64) = A_FILENAME,
255 // Syscalls permitted always
256 S(exit) = A_YES | A_SAMPLE_MEM,
269 S(ftruncate) = A_YES,
271 S(personality) = A_YES,
274 S(getresuid) = A_YES,
288 S(set_thread_area) = A_YES,
289 S(get_thread_area) = A_YES,
290 S(set_tid_address) = A_YES,
291 S(exit_group) = A_YES | A_SAMPLE_MEM,
292 #ifndef CONFIG_BOX_USER_AMD64
294 S(ftruncate64) = A_YES,
301 // Syscalls permitted only in liberal mode
302 S(time) = A_YES | A_LIBERAL,
303 S(alarm) = A_YES | A_LIBERAL,
304 S(pause) = A_YES | A_LIBERAL,
305 S(fchmod) = A_YES | A_LIBERAL,
306 S(getrlimit) = A_YES | A_LIBERAL,
307 S(getrusage) = A_YES | A_LIBERAL,
308 S(gettimeofday) = A_YES | A_LIBERAL,
309 S(select) = A_YES | A_LIBERAL,
310 S(setitimer) = A_YES | A_LIBERAL,
311 S(getitimer) = A_YES | A_LIBERAL,
312 S(mprotect) = A_YES | A_LIBERAL,
313 S(getdents) = A_YES | A_LIBERAL,
314 S(getdents64) = A_YES | A_LIBERAL,
315 S(fdatasync) = A_YES | A_LIBERAL,
316 S(mremap) = A_YES | A_LIBERAL,
317 S(poll) = A_YES | A_LIBERAL,
318 S(getcwd) = A_YES | A_LIBERAL,
319 S(nanosleep) = A_YES | A_LIBERAL,
320 S(rt_sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
321 S(rt_sigaction) = A_YES | A_LIBERAL,
322 S(rt_sigprocmask) = A_YES | A_LIBERAL,
323 S(rt_sigpending) = A_YES | A_LIBERAL,
324 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
325 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
326 S(rt_sigsuspend) = A_YES | A_LIBERAL,
327 S(_sysctl) = A_YES | A_LIBERAL,
328 #ifndef CONFIG_BOX_USER_AMD64
329 S(sigaction) = A_YES | A_LIBERAL,
330 S(sgetmask) = A_YES | A_LIBERAL,
331 S(ssetmask) = A_YES | A_LIBERAL,
332 S(sigsuspend) = A_YES | A_LIBERAL,
333 S(sigpending) = A_YES | A_LIBERAL,
334 S(sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
335 S(sigprocmask) = A_YES | A_LIBERAL,
336 S(ugetrlimit) = A_YES | A_LIBERAL,
337 S(readdir) = A_YES | A_LIBERAL,
338 S(signal) = A_YES | A_LIBERAL,
339 S(_newselect) = A_YES | A_LIBERAL,
346 syscall_name(unsigned int id, char *buf)
348 if (id < NUM_SYSCALLS && syscall_names[id])
349 return syscall_names[id];
352 sprintf(buf, "#%d", id);
358 syscall_by_name(char *name)
360 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
361 if (syscall_names[i] && !strcmp(syscall_names[i], name))
368 unsigned long l = strtoul(name, &ep, 0);
371 if (l >= NUM_ACTIONS)
377 set_syscall_action(char *a)
379 char *sep = strchr(a, '=');
380 enum action act = A_YES;
384 if (!strcmp(sep, "yes"))
386 else if (!strcmp(sep, "no"))
388 else if (!strcmp(sep, "file"))
394 int sys = syscall_by_name(a);
396 die("Unknown syscall `%s'", a);
397 if (sys >= NUM_ACTIONS)
398 die("Syscall `%s' out of range", a);
399 syscall_action[sys] = act;
408 struct path_rule *next;
411 static struct path_rule default_path_rules[] = {
414 { "/usr/lib/", A_YES },
415 { "/opt/lib/", A_YES },
416 { "/usr/share/zoneinfo/", A_YES },
417 { "/usr/share/locale/", A_YES },
418 { "/dev/null", A_YES },
419 { "/dev/zero", A_YES },
420 { "/proc/meminfo", A_YES },
421 { "/proc/self/stat", A_YES },
422 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
425 static struct path_rule *user_path_rules;
426 static struct path_rule **last_path_rule = &user_path_rules;
429 set_path_action(char *a)
431 char *sep = strchr(a, '=');
432 enum action act = A_YES;
436 if (!strcmp(sep, "yes"))
438 else if (!strcmp(sep, "no"))
444 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
445 r->path = (char *)(r+1);
450 last_path_rule = &r->next;
455 match_path_rule(struct path_rule *r, char *path)
459 if (*rr++ != *path++)
461 if (rr[-1] == '/' && !path[-1])
465 if (rr > r->path && rr[-1] != '/' && *path)
470 /*** Environment rules ***/
473 char *var; // Variable to match
474 char *val; // ""=clear, NULL=inherit
476 struct env_rule *next;
479 static struct env_rule *first_env_rule;
480 static struct env_rule **last_env_rule = &first_env_rule;
482 static struct env_rule default_env_rules[] = {
483 { "LIBC_FATAL_STDERR_", "1" }
487 set_env_action(char *a0)
489 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
490 char *a = (char *)(r+1);
493 char *sep = strchr(a, '=');
505 last_env_rule = &r->next;
511 match_env_var(char *env_entry, struct env_rule *r)
513 if (strncmp(env_entry, r->var, r->var_len))
515 return (env_entry[r->var_len] == '=');
519 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
521 // First remove the variable if already set
523 while (pos < *env_sizep && !match_env_var(env[pos], r))
525 if (pos < *env_sizep)
528 env[pos] = env[*env_sizep];
529 env[*env_sizep] = NULL;
532 // What is the new value?
538 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
539 sprintf(new, "%s=%s", r->var, r->val);
544 while (environ[pos] && !match_env_var(environ[pos], r))
546 if (!(new = environ[pos]))
550 // Add it at the end of the array
551 env[(*env_sizep)++] = new;
552 env[*env_sizep] = NULL;
556 setup_environment(void)
558 // Link built-in rules with user rules
559 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
561 default_env_rules[i].next = first_env_rule;
562 first_env_rule = &default_env_rules[i];
565 // Scan the original environment
566 char **orig_env = environ;
568 while (orig_env[orig_size])
571 // For each rule, reserve one more slot and calculate length
573 for (struct env_rule *r = first_env_rule; r; r=r->next)
576 r->var_len = strlen(r->var);
579 // Create a new environment
580 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
584 memcpy(env, environ, orig_size * sizeof(char *));
591 // Apply the rules one by one
592 for (struct env_rule *r = first_env_rule; r; r=r->next)
593 apply_env_rule(env, &size, r);
595 // Return the new env and pass some gossip
598 fprintf(stderr, "Passing environment:\n");
599 for (int i=0; env[i]; i++)
600 fprintf(stderr, "\t%s\n", env[i]);
605 /*** Low-level parsing of syscalls ***/
607 #ifdef CONFIG_BOX_KERNEL_AMD64
608 typedef uint64_t arg_t;
610 typedef uint32_t arg_t;
613 struct syscall_args {
615 arg_t arg1, arg2, arg3;
620 static int read_user_mem(arg_t addr, char *buf, int len)
627 sprintf(memname, "/proc/%d/mem", (int) box_pid);
628 mem_fd = open(memname, O_RDONLY);
630 die("open(%s): %m", memname);
632 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
633 die("lseek64(mem): %m");
634 return read(mem_fd, buf, len);
637 #ifdef CONFIG_BOX_KERNEL_AMD64
640 get_syscall_args(struct syscall_args *a, int is_exit)
642 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
643 die("ptrace(PTRACE_GETREGS): %m");
644 a->sys = a->user.regs.orig_rax;
645 a->result = a->user.regs.rax;
648 * CAVEAT: We have to check carefully that this is a real 64-bit syscall.
649 * We test whether the process runs in 64-bit mode, but surprisingly this
650 * is not enough: a 64-bit process can still issue the INT 0x80 instruction
651 * which performs a 32-bit syscall. Currently, the only known way how to
652 * detect this situation is to inspect the instruction code (the kernel
653 * keeps a syscall type flag internally, but it is not accessible from
654 * user space). Hopefully, there is no instruction whose suffix is the
655 * code of the SYSCALL instruction. Sometimes, one would wish the
656 * instruction codes to be unique even when read backwards :)
665 switch (a->user.regs.cs)
668 // 32-bit CPU mode => only 32-bit syscalls can be issued
673 if (read_user_mem(a->user.regs.rip-2, (char *) &instr, 2) != 2)
674 err("FO: Cannot read syscall instruction");
680 err("FO: Forbidden 32-bit syscall in 64-bit mode");
682 err("XX: Unknown syscall instruction %04x", instr);
687 err("XX: Unknown code segment %04jx", (intmax_t) a->user.regs.cs);
690 #ifdef CONFIG_BOX_USER_AMD64
692 err("FO: Forbidden %d-bit mode syscall", sys_type);
694 if (sys_type != (exec_seen ? 32 : 64))
695 err("FO: Forbidden %d-bit mode syscall", sys_type);
700 a->arg1 = a->user.regs.rbx;
701 a->arg2 = a->user.regs.rcx;
702 a->arg3 = a->user.regs.rdx;
706 a->arg1 = a->user.regs.rdi;
707 a->arg2 = a->user.regs.rsi;
708 a->arg3 = a->user.regs.rdx;
713 set_syscall_nr(struct syscall_args *a, arg_t sys)
716 a->user.regs.orig_rax = sys;
717 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
718 die("ptrace(PTRACE_SETREGS): %m");
724 get_syscall_args(struct syscall_args *a, int is_exit UNUSED)
726 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
727 die("ptrace(PTRACE_GETREGS): %m");
728 a->sys = a->user.regs.orig_eax;
729 a->arg1 = a->user.regs.ebx;
730 a->arg2 = a->user.regs.ecx;
731 a->arg3 = a->user.regs.edx;
732 a->result = a->user.regs.eax;
736 set_syscall_nr(struct syscall_args *a, arg_t sys)
739 a->user.regs.orig_eax = sys;
740 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
741 die("ptrace(PTRACE_SETREGS): %m");
746 /*** Syscall checks ***/
749 valid_filename(arg_t addr)
751 char namebuf[4096], *p, *end;
754 err("FA: File access forbidden");
755 if (file_access >= 9)
763 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
764 int l = namebuf + sizeof(namebuf) - end;
768 err("FA: Access to file with name too long");
769 remains = read_user_mem(addr, end, l);
771 die("read(mem): %m");
773 err("FA: Access to file with name out of memory");
780 msg("[%s] ", namebuf);
781 if (file_access >= 3)
784 // Everything in current directory is permitted
785 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
788 // ".." anywhere in the path is forbidden
789 enum action act = A_DEFAULT;
790 if (strstr(namebuf, ".."))
794 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
795 act = match_path_rule(r, namebuf);
797 // Scan built-in rules
798 if (file_access >= 2)
799 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
800 act = match_path_rule(&default_path_rules[i], namebuf);
803 err("FA: Forbidden access to file `%s'", namebuf);
806 // Check syscall. If invalid, return -1, otherwise return the action mask.
808 valid_syscall(struct syscall_args *a)
810 unsigned int sys = a->sys;
811 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
815 if (filter_syscalls != 1)
819 switch (act & A_ACTION_MASK)
826 valid_filename(a->arg1);
834 if (a->arg1 == (arg_t) box_pid)
836 meta_printf("exitsig:%d\n", (int) a->arg2);
837 err("SG: Committed suicide by signal %d", (int) a->arg2);
841 if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
843 meta_printf("exitsig:%d\n", (int) a->arg3);
844 err("SG: Committed suicide by signal %d", (int) a->arg3);
853 signal_alarm(int unused UNUSED)
855 /* Time limit checks are synchronous, so we only schedule them there. */
861 signal_int(int unused UNUSED)
863 /* Interrupts are fatal, so no synchronization requirements. */
864 meta_printf("exitsig:%d\n", SIGINT);
865 err("SG: Interrupted");
868 #define PROC_BUF_SIZE 4096
870 read_proc_file(char *buf, char *name, int *fdp)
876 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
877 *fdp = open(buf, O_RDONLY);
879 die("open(%s): %m", buf);
881 lseek(*fdp, 0, SEEK_SET);
882 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
883 die("read on /proc/$pid/%s: %m", name);
884 if (c >= PROC_BUF_SIZE-1)
885 die("/proc/$pid/%s too long", name);
894 struct timeval now, wall;
896 gettimeofday(&now, NULL);
897 timersub(&now, &start_time, &wall);
898 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
899 if (wall_ms > wall_timeout)
900 err("TO: Time limit exceeded (wall clock)");
902 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
906 char buf[PROC_BUF_SIZE], *x;
907 int utime, stime, ms;
908 static int proc_stat_fd;
909 read_proc_file(buf, "stat", &proc_stat_fd);
911 while (*x && *x != ' ')
916 die("proc stat syntax error 1");
917 while (*x && (*x != ')' || x[1] != ' '))
919 while (*x == ')' || *x == ' ')
921 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
922 die("proc stat syntax error 2");
923 ms = (utime + stime) * 1000 / ticks_per_sec;
925 fprintf(stderr, "[time check: %d msec]\n", ms);
926 if (ms > timeout && ms > extra_timeout)
927 err("TO: Time limit exceeded");
932 sample_mem_peak(void)
935 * We want to find out the peak memory usage of the process, which is
936 * maintained by the kernel, but unforunately it gets lost when the
937 * process exits (it is not reported in struct rusage). Therefore we
938 * have to sample it whenever we suspect that the process is about
941 char buf[PROC_BUF_SIZE], *x;
942 static int proc_status_fd;
943 read_proc_file(buf, "status", &proc_status_fd);
949 while (*x && *x != ':' && *x != '\n')
951 if (!*x || *x == '\n')
954 while (*x == ' ' || *x == '\t')
958 while (*x && *x != '\n')
964 if (!strcmp(key, "VmPeak"))
966 int peak = atoi(val);
967 if (peak > mem_peak_kb)
973 msg("[mem-peak: %u KB]\n", mem_peak_kb);
979 int syscall_count = (filter_syscalls ? 0 : 1);
984 bzero(&sa, sizeof(sa));
985 sa.sa_handler = signal_int;
986 sigaction(SIGINT, &sa, NULL);
988 gettimeofday(&start_time, NULL);
989 ticks_per_sec = sysconf(_SC_CLK_TCK);
990 if (ticks_per_sec <= 0)
991 die("Invalid ticks_per_sec!");
993 if (timeout || wall_timeout)
995 sa.sa_handler = signal_alarm;
996 sigaction(SIGALRM, &sa, NULL);
1010 p = wait4(box_pid, &stat, WUNTRACED, &rus);
1018 die("wait4: unknown pid %d exited!", p);
1019 if (WIFEXITED(stat))
1023 if (WEXITSTATUS(stat))
1027 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1028 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1032 // Internal error happened inside the child process and it has been already reported.
1036 if (timeout && total_ms > timeout)
1037 err("TO: Time limit exceeded");
1038 if (wall_timeout && wall_ms > wall_timeout)
1039 err("TO: Time limit exceeded (wall clock)");
1041 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
1042 total_ms/1000, total_ms%1000,
1043 wall_ms/1000, wall_ms%1000,
1044 (mem_peak_kb + 1023) / 1024,
1048 if (WIFSIGNALED(stat))
1051 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1053 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
1055 if (WIFSTOPPED(stat))
1057 int sig = WSTOPSIG(stat);
1061 msg("[ptrace status %08x] ", stat);
1062 static int stop_count;
1063 if (!stop_count++) /* Traceme request */
1064 msg(">> Traceme request caught\n");
1066 err("SG: Breakpoint");
1067 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1069 else if (sig == (SIGTRAP | 0x80))
1072 msg("[ptrace status %08x] ", stat);
1073 struct syscall_args a;
1074 static unsigned int sys_tick, last_act;
1075 static arg_t last_sys;
1076 if (++sys_tick & 1) /* Syscall entry */
1081 get_syscall_args(&a, 0);
1083 msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1087 if (sys == NATIVE_NR_execve)
1090 else if ((act = valid_syscall(&a)) >= 0)
1094 if (act & A_SAMPLE_MEM)
1100 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1101 * so we have to change it to something harmless (e.g., an undefined
1102 * syscall) and make the program continue.
1104 set_syscall_nr(&a, ~(arg_t)0);
1105 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1109 else /* Syscall return */
1111 get_syscall_args(&a, 1);
1112 if (a.sys == ~(arg_t)0)
1114 /* Some syscalls (sigreturn et al.) do not return a value */
1115 if (!(last_act & A_NO_RETVAL))
1116 err("XX: Syscall does not return, but it should");
1120 if (a.sys != last_sys)
1121 err("XX: Mismatched syscall entry/exit");
1123 if (last_act & A_NO_RETVAL)
1126 msg("= %jd\n", (intmax_t) a.result);
1128 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1130 else if (sig == SIGSTOP)
1132 msg(">> SIGSTOP\n");
1133 if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1134 die("ptrace(PTRACE_SETOPTIONS): %m");
1135 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1137 else if (sig != SIGXCPU && sig != SIGXFSZ)
1139 msg(">> Signal %d\n", sig);
1140 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
1141 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1145 meta_printf("exitsig:%d", sig);
1146 err("SG: Received signal %d", sig);
1150 die("wait4: unknown status %x, giving up!", stat);
1155 box_inside(int argc, char **argv)
1160 memcpy(args, argv, argc * sizeof(char *));
1162 if (set_cwd && chdir(set_cwd))
1167 if (open(redir_stdin, O_RDONLY) != 0)
1168 die("open(\"%s\"): %m", redir_stdin);
1173 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1174 die("open(\"%s\"): %m", redir_stdout);
1179 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1180 die("open(\"%s\"): %m", redir_stderr);
1188 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1189 if (setrlimit(RLIMIT_AS, &rl) < 0)
1190 die("setrlimit(RLIMIT_AS): %m");
1193 rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1194 if (setrlimit(RLIMIT_STACK, &rl) < 0)
1195 die("setrlimit(RLIMIT_STACK): %m");
1197 rl.rlim_cur = rl.rlim_max = 64;
1198 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1199 die("setrlimit(RLIMIT_NOFILE): %m");
1201 char **env = setup_environment();
1202 if (filter_syscalls)
1204 if (ptrace(PTRACE_TRACEME) < 0)
1205 die("ptrace(PTRACE_TRACEME): %m");
1206 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1209 execve(args[0], args, env);
1210 die("execve(\"%s\"): %m", args[0]);
1216 fprintf(stderr, "Invalid arguments!\n");
1218 Usage: box [<options>] -- <command> <arguments>\n\
1221 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1222 -c <dir>\tChange directory to <dir> first\n\
1223 -e\t\tInherit full environment of the parent process\n\
1224 -E <var>\tInherit the environment variable <var> from the parent process\n\
1225 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1226 -f\t\tFilter system calls (-ff=very restricted)\n\
1227 -i <file>\tRedirect stdin from <file>\n\
1228 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1229 -m <size>\tLimit address space to <size> KB\n\
1230 -M <file>\tOutput process information to <file> (name:value)\n\
1231 -o <file>\tRedirect stdout to <file>\n\
1232 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1233 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1234 -r <file>\tRedirect stderr to <file>\n\
1235 -s <sys>\tPermit the specified syscall (be careful)\n\
1236 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1237 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1238 -T\t\tAllow syscalls for measuring run time\n\
1239 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1240 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1241 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1242 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1248 main(int argc, char **argv)
1253 while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1257 file_access = atol(optarg);
1266 if (!set_env_action(optarg))
1273 stack_limit = atol(optarg);
1276 redir_stdin = optarg;
1279 memory_limit = atol(optarg);
1285 redir_stdout = optarg;
1288 if (!set_path_action(optarg))
1292 redir_stderr = optarg;
1295 if (!set_syscall_action(optarg))
1299 timeout = 1000*atof(optarg);
1302 syscall_action[__NR_times] = A_YES;
1308 wall_timeout = 1000*atof(optarg);
1311 extra_timeout = 1000*atof(optarg);
1320 if (setreuid(uid, uid) < 0)
1321 die("setreuid: %m");
1326 box_inside(argc-optind, argv+optind);
1329 die("Internal error: fell over edge of the world");