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 <sys/utsname.h>
28 #include <linux/ptrace.h>
30 #if defined(CONFIG_BOX_KERNEL_AMD64) && !defined(CONFIG_BOX_USER_AMD64)
31 #include <asm/unistd_32.h>
32 #define NATIVE_NR_execve 59 /* 64-bit execve */
34 #include <asm/unistd.h>
35 #define NATIVE_NR_execve __NR_execve
38 #define NONRET __attribute__((noreturn))
39 #define UNUSED __attribute__((unused))
40 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
42 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
43 static int timeout; /* milliseconds */
44 static int wall_timeout;
45 static int extra_timeout;
46 static int pass_environ;
47 static int file_access;
49 static int memory_limit;
50 static int stack_limit;
51 static char *redir_stdin, *redir_stdout, *redir_stderr;
55 static int is_ptraced;
56 static volatile int timer_tick;
57 static struct timeval start_time;
58 static int ticks_per_sec;
60 static int partial_line;
62 static int mem_peak_kb;
63 static int total_ms, wall_ms;
65 static void die(char *msg, ...) NONRET;
66 static void sample_mem_peak(void);
70 static FILE *metafile;
73 meta_open(const char *name)
75 if (!strcmp(name, "-"))
80 metafile = fopen(name, "w");
82 die("Failed to open metafile '%s'",name);
88 if (metafile && metafile != stdout)
92 static void __attribute__((format(printf,1,2)))
93 meta_printf(const char *fmt, ...)
100 vfprintf(metafile, fmt, args);
105 final_stats(struct rusage *rus)
107 struct timeval total, now, wall;
108 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
109 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
110 gettimeofday(&now, NULL);
111 timersub(&now, &start_time, &wall);
112 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
114 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
115 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
116 meta_printf("mem:%llu\n", (unsigned long long) mem_peak_kb * 1024);
119 /*** Messages and exits ***/
128 ptrace(PTRACE_KILL, box_pid);
129 kill(-box_pid, SIGKILL);
130 kill(box_pid, SIGKILL);
131 meta_printf("killed:1\n");
136 p = wait4(box_pid, &stat, 0, &rus);
137 while (p < 0 && errno == EINTR);
139 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
155 /* Report an error of the sandbox itself */
156 static void NONRET __attribute__((format(printf,1,2)))
163 vsnprintf(buf, sizeof(buf), msg, args);
164 meta_printf("status:XX\nmessage:%s\n", buf);
170 /* Report an error of the program inside the sandbox */
171 static void NONRET __attribute__((format(printf,1,2)))
177 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
179 meta_printf("status:%c%c\n", msg[0], msg[1]);
183 vsnprintf(buf, sizeof(buf), msg, args);
184 meta_printf("message:%s\n", buf);
190 /* Write a message, but only if in verbose mode */
191 static void __attribute__((format(printf,1,2)))
198 int len = strlen(msg);
200 partial_line = (msg[len-1] != '\n');
201 vfprintf(stderr, msg, args);
210 void *p = malloc(size);
212 die("Out of memory");
216 /*** Syscall rules ***/
218 static const char * const syscall_names[] = {
219 #include "box/syscall-table.h"
221 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
222 #define NUM_ACTIONS (NUM_SYSCALLS+64)
225 A_DEFAULT, // Use the default action
226 A_NO, // Always forbid
227 A_YES, // Always permit
228 A_FILENAME, // Permit if arg1 is a known filename
230 A_NO_RETVAL = 32, // Does not return a value
231 A_SAMPLE_MEM = 64, // Sample memory usage before the syscall
232 A_LIBERAL = 128, // Valid only in liberal mode
233 // Must fit in a unsigned char
236 static unsigned char syscall_action[NUM_ACTIONS] = {
237 #define S(x) [__NR_##x]
239 // Syscalls permitted for specific file names
240 S(open) = A_FILENAME,
241 S(creat) = A_FILENAME,
242 S(unlink) = A_FILENAME,
243 S(access) = A_FILENAME,
244 S(truncate) = A_FILENAME,
245 S(stat) = A_FILENAME,
246 S(lstat) = A_FILENAME,
247 S(readlink) = A_FILENAME,
248 #ifndef CONFIG_BOX_USER_AMD64
249 S(oldstat) = A_FILENAME,
250 S(oldlstat) = A_FILENAME,
251 S(truncate64) = A_FILENAME,
252 S(stat64) = A_FILENAME,
253 S(lstat64) = A_FILENAME,
256 // Syscalls permitted always
257 S(exit) = A_YES | A_SAMPLE_MEM,
270 S(ftruncate) = A_YES,
272 S(personality) = A_YES,
275 S(getresuid) = A_YES,
289 S(set_thread_area) = A_YES,
290 S(get_thread_area) = A_YES,
291 S(set_tid_address) = A_YES,
292 S(exit_group) = A_YES | A_SAMPLE_MEM,
293 #ifndef CONFIG_BOX_USER_AMD64
295 S(ftruncate64) = A_YES,
302 // Syscalls permitted only in liberal mode
303 S(time) = A_YES | A_LIBERAL,
304 S(alarm) = A_YES | A_LIBERAL,
305 S(pause) = A_YES | A_LIBERAL,
306 S(fchmod) = A_YES | A_LIBERAL,
307 S(getrlimit) = A_YES | A_LIBERAL,
308 S(getrusage) = A_YES | A_LIBERAL,
309 S(gettimeofday) = A_YES | A_LIBERAL,
310 S(select) = A_YES | A_LIBERAL,
311 S(setitimer) = A_YES | A_LIBERAL,
312 S(getitimer) = A_YES | A_LIBERAL,
313 S(mprotect) = A_YES | A_LIBERAL,
314 S(getdents) = A_YES | A_LIBERAL,
315 S(getdents64) = A_YES | A_LIBERAL,
316 S(fdatasync) = A_YES | A_LIBERAL,
317 S(mremap) = A_YES | A_LIBERAL,
318 S(poll) = A_YES | A_LIBERAL,
319 S(getcwd) = A_YES | A_LIBERAL,
320 S(nanosleep) = A_YES | A_LIBERAL,
321 S(rt_sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
322 S(rt_sigaction) = A_YES | A_LIBERAL,
323 S(rt_sigprocmask) = A_YES | A_LIBERAL,
324 S(rt_sigpending) = A_YES | A_LIBERAL,
325 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
326 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
327 S(rt_sigsuspend) = A_YES | A_LIBERAL,
328 S(_sysctl) = A_YES | A_LIBERAL,
329 #ifndef CONFIG_BOX_USER_AMD64
330 S(sigaction) = A_YES | A_LIBERAL,
331 S(sgetmask) = A_YES | A_LIBERAL,
332 S(ssetmask) = A_YES | A_LIBERAL,
333 S(sigsuspend) = A_YES | A_LIBERAL,
334 S(sigpending) = A_YES | A_LIBERAL,
335 S(sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
336 S(sigprocmask) = A_YES | A_LIBERAL,
337 S(ugetrlimit) = A_YES | A_LIBERAL,
338 S(readdir) = A_YES | A_LIBERAL,
339 S(signal) = A_YES | A_LIBERAL,
340 S(_newselect) = A_YES | A_LIBERAL,
347 syscall_name(unsigned int id, char *buf)
349 if (id < NUM_SYSCALLS && syscall_names[id])
350 return syscall_names[id];
353 sprintf(buf, "#%d", id);
359 syscall_by_name(char *name)
361 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
362 if (syscall_names[i] && !strcmp(syscall_names[i], name))
369 unsigned long l = strtoul(name, &ep, 0);
372 if (l >= NUM_ACTIONS)
378 set_syscall_action(char *a)
380 char *sep = strchr(a, '=');
381 enum action act = A_YES;
385 if (!strcmp(sep, "yes"))
387 else if (!strcmp(sep, "no"))
389 else if (!strcmp(sep, "file"))
395 int sys = syscall_by_name(a);
397 die("Unknown syscall `%s'", a);
398 if (sys >= NUM_ACTIONS)
399 die("Syscall `%s' out of range", a);
400 syscall_action[sys] = act;
409 struct path_rule *next;
412 static struct path_rule default_path_rules[] = {
415 { "/usr/lib/", A_YES },
416 { "/opt/lib/", A_YES },
417 { "/usr/share/zoneinfo/", A_YES },
418 { "/usr/share/locale/", A_YES },
419 { "/dev/null", A_YES },
420 { "/dev/zero", A_YES },
421 { "/proc/meminfo", A_YES },
422 { "/proc/self/stat", A_YES },
423 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
426 static struct path_rule *user_path_rules;
427 static struct path_rule **last_path_rule = &user_path_rules;
430 set_path_action(char *a)
432 char *sep = strchr(a, '=');
433 enum action act = A_YES;
437 if (!strcmp(sep, "yes"))
439 else if (!strcmp(sep, "no"))
445 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
446 r->path = (char *)(r+1);
451 last_path_rule = &r->next;
456 match_path_rule(struct path_rule *r, char *path)
460 if (*rr++ != *path++)
462 if (rr[-1] == '/' && !path[-1])
466 if (rr > r->path && rr[-1] != '/' && *path)
471 /*** Environment rules ***/
474 char *var; // Variable to match
475 char *val; // ""=clear, NULL=inherit
477 struct env_rule *next;
480 static struct env_rule *first_env_rule;
481 static struct env_rule **last_env_rule = &first_env_rule;
483 static struct env_rule default_env_rules[] = {
484 { "LIBC_FATAL_STDERR_", "1" }
488 set_env_action(char *a0)
490 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
491 char *a = (char *)(r+1);
494 char *sep = strchr(a, '=');
506 last_env_rule = &r->next;
512 match_env_var(char *env_entry, struct env_rule *r)
514 if (strncmp(env_entry, r->var, r->var_len))
516 return (env_entry[r->var_len] == '=');
520 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
522 // First remove the variable if already set
524 while (pos < *env_sizep && !match_env_var(env[pos], r))
526 if (pos < *env_sizep)
529 env[pos] = env[*env_sizep];
530 env[*env_sizep] = NULL;
533 // What is the new value?
539 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
540 sprintf(new, "%s=%s", r->var, r->val);
545 while (environ[pos] && !match_env_var(environ[pos], r))
547 if (!(new = environ[pos]))
551 // Add it at the end of the array
552 env[(*env_sizep)++] = new;
553 env[*env_sizep] = NULL;
557 setup_environment(void)
559 // Link built-in rules with user rules
560 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
562 default_env_rules[i].next = first_env_rule;
563 first_env_rule = &default_env_rules[i];
566 // Scan the original environment
567 char **orig_env = environ;
569 while (orig_env[orig_size])
572 // For each rule, reserve one more slot and calculate length
574 for (struct env_rule *r = first_env_rule; r; r=r->next)
577 r->var_len = strlen(r->var);
580 // Create a new environment
581 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
585 memcpy(env, environ, orig_size * sizeof(char *));
592 // Apply the rules one by one
593 for (struct env_rule *r = first_env_rule; r; r=r->next)
594 apply_env_rule(env, &size, r);
596 // Return the new env and pass some gossip
599 fprintf(stderr, "Passing environment:\n");
600 for (int i=0; env[i]; i++)
601 fprintf(stderr, "\t%s\n", env[i]);
606 /*** Low-level parsing of syscalls ***/
608 #ifdef CONFIG_BOX_KERNEL_AMD64
609 typedef uint64_t arg_t;
611 typedef uint32_t arg_t;
614 struct syscall_args {
616 arg_t arg1, arg2, arg3;
621 static int read_user_mem(arg_t addr, char *buf, int len)
628 sprintf(memname, "/proc/%d/mem", (int) box_pid);
629 mem_fd = open(memname, O_RDONLY);
631 die("open(%s): %m", memname);
633 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
634 die("lseek64(mem): %m");
635 return read(mem_fd, buf, len);
638 #ifdef CONFIG_BOX_KERNEL_AMD64
641 get_syscall_args(struct syscall_args *a, int is_exit)
643 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
644 die("ptrace(PTRACE_GETREGS): %m");
645 a->sys = a->user.regs.orig_rax;
646 a->result = a->user.regs.rax;
649 * CAVEAT: We have to check carefully that this is a real 64-bit syscall.
650 * We test whether the process runs in 64-bit mode, but surprisingly this
651 * is not enough: a 64-bit process can still issue the INT 0x80 instruction
652 * which performs a 32-bit syscall. Currently, the only known way how to
653 * detect this situation is to inspect the instruction code (the kernel
654 * keeps a syscall type flag internally, but it is not accessible from
655 * user space). Hopefully, there is no instruction whose suffix is the
656 * code of the SYSCALL instruction. Sometimes, one would wish the
657 * instruction codes to be unique even when read backwards :)
666 switch (a->user.regs.cs)
669 // 32-bit CPU mode => only 32-bit syscalls can be issued
674 if (read_user_mem(a->user.regs.rip-2, (char *) &instr, 2) != 2)
675 err("FO: Cannot read syscall instruction");
681 err("FO: Forbidden 32-bit syscall in 64-bit mode");
683 err("XX: Unknown syscall instruction %04x", instr);
688 err("XX: Unknown code segment %04jx", (intmax_t) a->user.regs.cs);
691 #ifdef CONFIG_BOX_USER_AMD64
693 err("FO: Forbidden %d-bit mode syscall", sys_type);
695 if (sys_type != (exec_seen ? 32 : 64))
696 err("FO: Forbidden %d-bit mode syscall", sys_type);
701 a->arg1 = a->user.regs.rbx;
702 a->arg2 = a->user.regs.rcx;
703 a->arg3 = a->user.regs.rdx;
707 a->arg1 = a->user.regs.rdi;
708 a->arg2 = a->user.regs.rsi;
709 a->arg3 = a->user.regs.rdx;
714 set_syscall_nr(struct syscall_args *a, arg_t sys)
717 a->user.regs.orig_rax = sys;
718 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
719 die("ptrace(PTRACE_SETREGS): %m");
730 get_syscall_args(struct syscall_args *a, int is_exit UNUSED)
732 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
733 die("ptrace(PTRACE_GETREGS): %m");
734 a->sys = a->user.regs.orig_eax;
735 a->arg1 = a->user.regs.ebx;
736 a->arg2 = a->user.regs.ecx;
737 a->arg3 = a->user.regs.edx;
738 a->result = a->user.regs.eax;
742 set_syscall_nr(struct syscall_args *a, arg_t sys)
745 a->user.regs.orig_eax = sys;
746 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
747 die("ptrace(PTRACE_SETREGS): %m");
753 #if !defined(CONFIG_BOX_ALLOW_INSECURE)
756 die("uname() failed: %m");
758 if (!strcmp(uts.machine, "x86_64"))
759 die("Running 32-bit sandbox on 64-bit kernels is inherently unsafe. Please get a 64-bit version.");
765 /*** Syscall checks ***/
768 valid_filename(arg_t addr)
770 char namebuf[4096], *p, *end;
773 err("FA: File access forbidden");
774 if (file_access >= 9)
782 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
783 int l = namebuf + sizeof(namebuf) - end;
787 err("FA: Access to file with name too long");
788 remains = read_user_mem(addr, end, l);
790 die("read(mem): %m");
792 err("FA: Access to file with name out of memory");
799 msg("[%s] ", namebuf);
800 if (file_access >= 3)
803 // Everything in current directory is permitted
804 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
807 // ".." anywhere in the path is forbidden
808 enum action act = A_DEFAULT;
809 if (strstr(namebuf, ".."))
813 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
814 act = match_path_rule(r, namebuf);
816 // Scan built-in rules
817 if (file_access >= 2)
818 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
819 act = match_path_rule(&default_path_rules[i], namebuf);
822 err("FA: Forbidden access to file `%s'", namebuf);
825 // Check syscall. If invalid, return -1, otherwise return the action mask.
827 valid_syscall(struct syscall_args *a)
829 unsigned int sys = a->sys;
830 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
834 if (filter_syscalls != 1)
838 switch (act & A_ACTION_MASK)
845 valid_filename(a->arg1);
853 if (a->arg1 == (arg_t) box_pid)
855 meta_printf("exitsig:%d\n", (int) a->arg2);
856 err("SG: Committed suicide by signal %d", (int) a->arg2);
860 if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
862 meta_printf("exitsig:%d\n", (int) a->arg3);
863 err("SG: Committed suicide by signal %d", (int) a->arg3);
872 signal_alarm(int unused UNUSED)
874 /* Time limit checks are synchronous, so we only schedule them there. */
880 signal_int(int unused UNUSED)
882 /* Interrupts are fatal, so no synchronization requirements. */
883 meta_printf("exitsig:%d\n", SIGINT);
884 err("SG: Interrupted");
887 #define PROC_BUF_SIZE 4096
889 read_proc_file(char *buf, char *name, int *fdp)
895 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
896 *fdp = open(buf, O_RDONLY);
898 die("open(%s): %m", buf);
900 lseek(*fdp, 0, SEEK_SET);
901 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
902 die("read on /proc/$pid/%s: %m", name);
903 if (c >= PROC_BUF_SIZE-1)
904 die("/proc/$pid/%s too long", name);
913 struct timeval now, wall;
915 gettimeofday(&now, NULL);
916 timersub(&now, &start_time, &wall);
917 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
918 if (wall_ms > wall_timeout)
919 err("TO: Time limit exceeded (wall clock)");
921 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
925 char buf[PROC_BUF_SIZE], *x;
926 int utime, stime, ms;
927 static int proc_stat_fd;
928 read_proc_file(buf, "stat", &proc_stat_fd);
930 while (*x && *x != ' ')
935 die("proc stat syntax error 1");
936 while (*x && (*x != ')' || x[1] != ' '))
938 while (*x == ')' || *x == ' ')
940 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
941 die("proc stat syntax error 2");
942 ms = (utime + stime) * 1000 / ticks_per_sec;
944 fprintf(stderr, "[time check: %d msec]\n", ms);
945 if (ms > timeout && ms > extra_timeout)
946 err("TO: Time limit exceeded");
951 sample_mem_peak(void)
954 * We want to find out the peak memory usage of the process, which is
955 * maintained by the kernel, but unforunately it gets lost when the
956 * process exits (it is not reported in struct rusage). Therefore we
957 * have to sample it whenever we suspect that the process is about
960 char buf[PROC_BUF_SIZE], *x;
961 static int proc_status_fd;
962 read_proc_file(buf, "status", &proc_status_fd);
968 while (*x && *x != ':' && *x != '\n')
970 if (!*x || *x == '\n')
973 while (*x == ' ' || *x == '\t')
977 while (*x && *x != '\n')
983 if (!strcmp(key, "VmPeak"))
985 int peak = atoi(val);
986 if (peak > mem_peak_kb)
992 msg("[mem-peak: %u KB]\n", mem_peak_kb);
998 int syscall_count = (filter_syscalls ? 0 : 1);
1003 bzero(&sa, sizeof(sa));
1004 sa.sa_handler = signal_int;
1005 sigaction(SIGINT, &sa, NULL);
1007 gettimeofday(&start_time, NULL);
1008 ticks_per_sec = sysconf(_SC_CLK_TCK);
1009 if (ticks_per_sec <= 0)
1010 die("Invalid ticks_per_sec!");
1012 if (timeout || wall_timeout)
1014 sa.sa_handler = signal_alarm;
1015 sigaction(SIGALRM, &sa, NULL);
1029 p = wait4(box_pid, &stat, WUNTRACED, &rus);
1037 die("wait4: unknown pid %d exited!", p);
1038 if (WIFEXITED(stat))
1042 if (WEXITSTATUS(stat))
1046 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
1047 err("RE: Exited with error status %d", WEXITSTATUS(stat));
1051 // Internal error happened inside the child process and it has been already reported.
1055 if (timeout && total_ms > timeout)
1056 err("TO: Time limit exceeded");
1057 if (wall_timeout && wall_ms > wall_timeout)
1058 err("TO: Time limit exceeded (wall clock)");
1060 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
1061 total_ms/1000, total_ms%1000,
1062 wall_ms/1000, wall_ms%1000,
1063 (mem_peak_kb + 1023) / 1024,
1067 if (WIFSIGNALED(stat))
1070 meta_printf("exitsig:%d\n", WTERMSIG(stat));
1072 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
1074 if (WIFSTOPPED(stat))
1076 int sig = WSTOPSIG(stat);
1080 msg("[ptrace status %08x] ", stat);
1081 static int stop_count;
1082 if (!stop_count++) /* Traceme request */
1083 msg(">> Traceme request caught\n");
1085 err("SG: Breakpoint");
1086 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1088 else if (sig == (SIGTRAP | 0x80))
1091 msg("[ptrace status %08x] ", stat);
1092 struct syscall_args a;
1093 static unsigned int sys_tick, last_act;
1094 static arg_t last_sys;
1095 if (++sys_tick & 1) /* Syscall entry */
1100 get_syscall_args(&a, 0);
1102 msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1106 if (sys == NATIVE_NR_execve)
1109 else if ((act = valid_syscall(&a)) >= 0)
1113 if (act & A_SAMPLE_MEM)
1119 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1120 * so we have to change it to something harmless (e.g., an undefined
1121 * syscall) and make the program continue.
1123 set_syscall_nr(&a, ~(arg_t)0);
1124 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1128 else /* Syscall return */
1130 get_syscall_args(&a, 1);
1131 if (a.sys == ~(arg_t)0)
1133 /* Some syscalls (sigreturn et al.) do not return a value */
1134 if (!(last_act & A_NO_RETVAL))
1135 err("XX: Syscall does not return, but it should");
1139 if (a.sys != last_sys)
1140 err("XX: Mismatched syscall entry/exit");
1142 if (last_act & A_NO_RETVAL)
1145 msg("= %jd\n", (intmax_t) a.result);
1147 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1149 else if (sig == SIGSTOP)
1151 msg(">> SIGSTOP\n");
1152 if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1153 die("ptrace(PTRACE_SETOPTIONS): %m");
1154 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1156 else if (sig != SIGXCPU && sig != SIGXFSZ)
1158 msg(">> Signal %d\n", sig);
1159 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
1160 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1164 meta_printf("exitsig:%d", sig);
1165 err("SG: Received signal %d", sig);
1169 die("wait4: unknown status %x, giving up!", stat);
1174 box_inside(int argc, char **argv)
1179 memcpy(args, argv, argc * sizeof(char *));
1181 if (set_cwd && chdir(set_cwd))
1186 if (open(redir_stdin, O_RDONLY) != 0)
1187 die("open(\"%s\"): %m", redir_stdin);
1192 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1193 die("open(\"%s\"): %m", redir_stdout);
1198 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1199 die("open(\"%s\"): %m", redir_stderr);
1207 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1208 if (setrlimit(RLIMIT_AS, &rl) < 0)
1209 die("setrlimit(RLIMIT_AS): %m");
1212 rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1213 if (setrlimit(RLIMIT_STACK, &rl) < 0)
1214 die("setrlimit(RLIMIT_STACK): %m");
1216 rl.rlim_cur = rl.rlim_max = 64;
1217 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1218 die("setrlimit(RLIMIT_NOFILE): %m");
1220 char **env = setup_environment();
1221 if (filter_syscalls)
1223 if (ptrace(PTRACE_TRACEME) < 0)
1224 die("ptrace(PTRACE_TRACEME): %m");
1225 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1228 execve(args[0], args, env);
1229 die("execve(\"%s\"): %m", args[0]);
1235 fprintf(stderr, "Invalid arguments!\n");
1237 Usage: box [<options>] -- <command> <arguments>\n\
1240 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1241 -c <dir>\tChange directory to <dir> first\n\
1242 -e\t\tInherit full environment of the parent process\n\
1243 -E <var>\tInherit the environment variable <var> from the parent process\n\
1244 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1245 -f\t\tFilter system calls (-ff=very restricted)\n\
1246 -i <file>\tRedirect stdin from <file>\n\
1247 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1248 -m <size>\tLimit address space to <size> KB\n\
1249 -M <file>\tOutput process information to <file> (name:value)\n\
1250 -o <file>\tRedirect stdout to <file>\n\
1251 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1252 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1253 -r <file>\tRedirect stderr to <file>\n\
1254 -s <sys>\tPermit the specified syscall (be careful)\n\
1255 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1256 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1257 -T\t\tAllow syscalls for measuring run time\n\
1258 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1259 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1260 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1261 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1267 main(int argc, char **argv)
1272 while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1276 file_access = atol(optarg);
1285 if (!set_env_action(optarg))
1292 stack_limit = atol(optarg);
1295 redir_stdin = optarg;
1298 memory_limit = atol(optarg);
1304 redir_stdout = optarg;
1307 if (!set_path_action(optarg))
1311 redir_stderr = optarg;
1314 if (!set_syscall_action(optarg))
1318 timeout = 1000*atof(optarg);
1321 syscall_action[__NR_times] = A_YES;
1327 wall_timeout = 1000*atof(optarg);
1330 extra_timeout = 1000*atof(optarg);
1340 if (setreuid(uid, uid) < 0)
1341 die("setreuid: %m");
1346 box_inside(argc-optind, argv+optind);
1349 die("Internal error: fell over edge of the world");