2 * A Simple Sandbox for Moe
4 * (c) 2001--2010 Martin Mares <mj@ucw.cz>
7 #define _LARGEFILE64_SOURCE
23 #include <sys/ptrace.h>
24 #include <sys/signal.h>
25 #include <sys/sysinfo.h>
26 #include <sys/syscall.h>
27 #include <sys/resource.h>
28 #include <linux/ptrace.h>
30 #define NONRET __attribute__((noreturn))
31 #define UNUSED __attribute__((unused))
32 #define ARRAY_SIZE(a) (int)(sizeof(a)/sizeof(a[0]))
34 static int filter_syscalls; /* 0=off, 1=liberal, 2=totalitarian */
35 static int timeout; /* milliseconds */
36 static int wall_timeout;
37 static int extra_timeout;
38 static int pass_environ;
39 static int file_access;
41 static int memory_limit;
42 static int stack_limit;
43 static char *redir_stdin, *redir_stdout, *redir_stderr;
47 static int is_ptraced;
48 static volatile int timer_tick;
49 static struct timeval start_time;
50 static int ticks_per_sec;
52 static int partial_line;
54 static int mem_peak_kb;
55 static int total_ms, wall_ms;
57 static void die(char *msg, ...) NONRET;
58 static void sample_mem_peak(void);
62 static FILE *metafile;
65 meta_open(const char *name)
67 if (!strcmp(name, "-"))
72 metafile = fopen(name, "w");
74 die("Failed to open metafile '%s'",name);
80 if (metafile && metafile != stdout)
84 static void __attribute__((format(printf,1,2)))
85 meta_printf(const char *fmt, ...)
92 vfprintf(metafile, fmt, args);
97 final_stats(struct rusage *rus)
99 struct timeval total, now, wall;
100 timeradd(&rus->ru_utime, &rus->ru_stime, &total);
101 total_ms = total.tv_sec*1000 + total.tv_usec/1000;
102 gettimeofday(&now, NULL);
103 timersub(&now, &start_time, &wall);
104 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
106 meta_printf("time:%d.%03d\n", total_ms/1000, total_ms%1000);
107 meta_printf("time-wall:%d.%03d\n", wall_ms/1000, wall_ms%1000);
108 meta_printf("mem:%llu\n", (unsigned long long) mem_peak_kb * 1024);
111 /*** Messages and exits ***/
120 ptrace(PTRACE_KILL, box_pid);
121 kill(-box_pid, SIGKILL);
122 kill(box_pid, SIGKILL);
123 meta_printf("killed:1\n");
128 p = wait4(box_pid, &stat, 0, &rus);
129 while (p < 0 && errno == EINTR);
131 fprintf(stderr, "UGH: Lost track of the process (%m)\n");
147 /* Report an error of the sandbox itself */
148 static void NONRET __attribute__((format(printf,1,2)))
155 vsnprintf(buf, sizeof(buf), msg, args);
156 meta_printf("status:XX\nmessage:%s\n", buf);
162 /* Report an error of the program inside the sandbox */
163 static void NONRET __attribute__((format(printf,1,2)))
169 if (msg[0] && msg[1] && msg[2] == ':' && msg[3] == ' ')
171 meta_printf("status:%c%c\n", msg[0], msg[1]);
175 vsnprintf(buf, sizeof(buf), msg, args);
176 meta_printf("message:%s\n", buf);
182 /* Write a message, but only if in verbose mode */
183 static void __attribute__((format(printf,1,2)))
190 int len = strlen(msg);
192 partial_line = (msg[len-1] != '\n');
193 vfprintf(stderr, msg, args);
202 void *p = malloc(size);
204 die("Out of memory");
208 /*** Syscall rules ***/
210 static const char * const syscall_names[] = {
211 #include "box/syscall-table.h"
213 #define NUM_SYSCALLS ARRAY_SIZE(syscall_names)
214 #define NUM_ACTIONS (NUM_SYSCALLS+64)
217 A_DEFAULT, // Use the default action
218 A_NO, // Always forbid
219 A_YES, // Always permit
220 A_FILENAME, // Permit if arg1 is a known filename
222 A_NO_RETVAL = 32, // Does not return a value
223 A_SAMPLE_MEM = 64, // Sample memory usage before the syscall
224 A_LIBERAL = 128, // Valid only in liberal mode
225 // Must fit in a unsigned char
228 static unsigned char syscall_action[NUM_ACTIONS] = {
229 #define S(x) [__NR_##x]
231 // Syscalls permitted for specific file names
232 S(open) = A_FILENAME,
233 S(creat) = A_FILENAME,
234 S(unlink) = A_FILENAME,
235 S(access) = A_FILENAME,
236 S(truncate) = A_FILENAME,
237 S(stat) = A_FILENAME,
238 S(lstat) = A_FILENAME,
239 S(readlink) = A_FILENAME,
240 #ifndef CONFIG_BOX_AMD64
241 S(oldstat) = A_FILENAME,
242 S(oldlstat) = A_FILENAME,
243 S(truncate64) = A_FILENAME,
244 S(stat64) = A_FILENAME,
245 S(lstat64) = A_FILENAME,
248 // Syscalls permitted always
249 S(exit) = A_YES | A_SAMPLE_MEM,
262 S(ftruncate) = A_YES,
264 S(personality) = A_YES,
267 S(getresuid) = A_YES,
281 S(set_thread_area) = A_YES,
282 S(get_thread_area) = A_YES,
283 S(set_tid_address) = A_YES,
284 S(exit_group) = A_YES | A_SAMPLE_MEM,
285 #ifndef CONFIG_BOX_AMD64
287 S(ftruncate64) = A_YES,
294 // Syscalls permitted only in liberal mode
295 S(time) = A_YES | A_LIBERAL,
296 S(alarm) = A_YES | A_LIBERAL,
297 S(pause) = A_YES | A_LIBERAL,
298 S(fchmod) = A_YES | A_LIBERAL,
299 S(getrlimit) = A_YES | A_LIBERAL,
300 S(getrusage) = A_YES | A_LIBERAL,
301 S(gettimeofday) = A_YES | A_LIBERAL,
302 S(select) = A_YES | A_LIBERAL,
303 S(setitimer) = A_YES | A_LIBERAL,
304 S(getitimer) = A_YES | A_LIBERAL,
305 S(mprotect) = A_YES | A_LIBERAL,
306 S(getdents) = A_YES | A_LIBERAL,
307 S(getdents64) = A_YES | A_LIBERAL,
308 S(fdatasync) = A_YES | A_LIBERAL,
309 S(mremap) = A_YES | A_LIBERAL,
310 S(poll) = A_YES | A_LIBERAL,
311 S(getcwd) = A_YES | A_LIBERAL,
312 S(nanosleep) = A_YES | A_LIBERAL,
313 S(rt_sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
314 S(rt_sigaction) = A_YES | A_LIBERAL,
315 S(rt_sigprocmask) = A_YES | A_LIBERAL,
316 S(rt_sigpending) = A_YES | A_LIBERAL,
317 S(rt_sigtimedwait) = A_YES | A_LIBERAL,
318 S(rt_sigqueueinfo) = A_YES | A_LIBERAL,
319 S(rt_sigsuspend) = A_YES | A_LIBERAL,
320 S(_sysctl) = A_YES | A_LIBERAL,
321 #ifndef CONFIG_BOX_AMD64
322 S(sigaction) = A_YES | A_LIBERAL,
323 S(sgetmask) = A_YES | A_LIBERAL,
324 S(ssetmask) = A_YES | A_LIBERAL,
325 S(sigsuspend) = A_YES | A_LIBERAL,
326 S(sigpending) = A_YES | A_LIBERAL,
327 S(sigreturn) = A_YES | A_LIBERAL | A_NO_RETVAL,
328 S(sigprocmask) = A_YES | A_LIBERAL,
329 S(ugetrlimit) = A_YES | A_LIBERAL,
330 S(readdir) = A_YES | A_LIBERAL,
331 S(signal) = A_YES | A_LIBERAL,
332 S(_newselect) = A_YES | A_LIBERAL,
339 syscall_name(unsigned int id, char *buf)
341 if (id < NUM_SYSCALLS && syscall_names[id])
342 return syscall_names[id];
345 sprintf(buf, "#%d", id);
351 syscall_by_name(char *name)
353 for (unsigned int i=0; i<NUM_SYSCALLS; i++)
354 if (syscall_names[i] && !strcmp(syscall_names[i], name))
361 unsigned long l = strtoul(name, &ep, 0);
364 if (l >= NUM_ACTIONS)
370 set_syscall_action(char *a)
372 char *sep = strchr(a, '=');
373 enum action act = A_YES;
377 if (!strcmp(sep, "yes"))
379 else if (!strcmp(sep, "no"))
381 else if (!strcmp(sep, "file"))
387 int sys = syscall_by_name(a);
389 die("Unknown syscall `%s'", a);
390 if (sys >= NUM_ACTIONS)
391 die("Syscall `%s' out of range", a);
392 syscall_action[sys] = act;
401 struct path_rule *next;
404 static struct path_rule default_path_rules[] = {
407 { "/usr/lib/", A_YES },
408 { "/opt/lib/", A_YES },
409 { "/usr/share/zoneinfo/", A_YES },
410 { "/usr/share/locale/", A_YES },
411 { "/dev/null", A_YES },
412 { "/dev/zero", A_YES },
413 { "/proc/meminfo", A_YES },
414 { "/proc/self/stat", A_YES },
415 { "/proc/self/exe", A_YES }, // Needed by FPC 2.0.x runtime
418 static struct path_rule *user_path_rules;
419 static struct path_rule **last_path_rule = &user_path_rules;
422 set_path_action(char *a)
424 char *sep = strchr(a, '=');
425 enum action act = A_YES;
429 if (!strcmp(sep, "yes"))
431 else if (!strcmp(sep, "no"))
437 struct path_rule *r = xmalloc(sizeof(*r) + strlen(a) + 1);
438 r->path = (char *)(r+1);
443 last_path_rule = &r->next;
448 match_path_rule(struct path_rule *r, char *path)
452 if (*rr++ != *path++)
454 if (rr[-1] == '/' && !path[-1])
458 if (rr > r->path && rr[-1] != '/' && *path)
463 /*** Environment rules ***/
466 char *var; // Variable to match
467 char *val; // ""=clear, NULL=inherit
469 struct env_rule *next;
472 static struct env_rule *first_env_rule;
473 static struct env_rule **last_env_rule = &first_env_rule;
475 static struct env_rule default_env_rules[] = {
476 { "LIBC_FATAL_STDERR_", "1" }
480 set_env_action(char *a0)
482 struct env_rule *r = xmalloc(sizeof(*r) + strlen(a0) + 1);
483 char *a = (char *)(r+1);
486 char *sep = strchr(a, '=');
498 last_env_rule = &r->next;
504 match_env_var(char *env_entry, struct env_rule *r)
506 if (strncmp(env_entry, r->var, r->var_len))
508 return (env_entry[r->var_len] == '=');
512 apply_env_rule(char **env, int *env_sizep, struct env_rule *r)
514 // First remove the variable if already set
516 while (pos < *env_sizep && !match_env_var(env[pos], r))
518 if (pos < *env_sizep)
521 env[pos] = env[*env_sizep];
522 env[*env_sizep] = NULL;
525 // What is the new value?
531 new = xmalloc(r->var_len + 1 + strlen(r->val) + 1);
532 sprintf(new, "%s=%s", r->var, r->val);
537 while (environ[pos] && !match_env_var(environ[pos], r))
539 if (!(new = environ[pos]))
543 // Add it at the end of the array
544 env[(*env_sizep)++] = new;
545 env[*env_sizep] = NULL;
549 setup_environment(void)
551 // Link built-in rules with user rules
552 for (int i=ARRAY_SIZE(default_env_rules)-1; i >= 0; i--)
554 default_env_rules[i].next = first_env_rule;
555 first_env_rule = &default_env_rules[i];
558 // Scan the original environment
559 char **orig_env = environ;
561 while (orig_env[orig_size])
564 // For each rule, reserve one more slot and calculate length
566 for (struct env_rule *r = first_env_rule; r; r=r->next)
569 r->var_len = strlen(r->var);
572 // Create a new environment
573 char **env = xmalloc((orig_size + num_rules + 1) * sizeof(char *));
577 memcpy(env, environ, orig_size * sizeof(char *));
584 // Apply the rules one by one
585 for (struct env_rule *r = first_env_rule; r; r=r->next)
586 apply_env_rule(env, &size, r);
588 // Return the new env and pass some gossip
591 fprintf(stderr, "Passing environment:\n");
592 for (int i=0; env[i]; i++)
593 fprintf(stderr, "\t%s\n", env[i]);
598 /*** Low-level parsing of syscalls ***/
600 #ifdef CONFIG_BOX_AMD64
601 typedef uint64_t arg_t;
603 typedef uint32_t arg_t;
606 struct syscall_args {
608 arg_t arg1, arg2, arg3;
613 #ifdef CONFIG_BOX_AMD64
616 get_syscall_args(struct syscall_args *a)
618 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
619 die("ptrace(PTRACE_GETREGS): %m");
620 a->sys = a->user.regs.orig_rax;
621 a->arg1 = a->user.regs.rdi;
622 a->arg2 = a->user.regs.rsi;
623 a->arg3 = a->user.regs.rdx;
624 a->result = a->user.regs.rax;
626 // FIXME: Check that it's really a 64-bit syscall
630 set_syscall_nr(struct syscall_args *a, arg_t sys)
633 a->user.regs.orig_rax = sys;
634 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
635 die("ptrace(PTRACE_SETREGS): %m");
641 get_syscall_args(struct syscall_args *a)
643 if (ptrace(PTRACE_GETREGS, box_pid, NULL, &a->user) < 0)
644 die("ptrace(PTRACE_GETREGS): %m");
645 a->sys = a->user.regs.orig_eax;
646 a->arg1 = a->user.regs.ebx;
647 a->arg2 = a->user.regs.ecx;
648 a->arg3 = a->user.regs.edx;
649 a->result = a->user.regs.eax;
653 set_syscall_nr(struct syscall_args *a, arg_t sys)
656 a->user.regs.orig_eax = sys;
657 if (ptrace(PTRACE_SETREGS, box_pid, NULL, &a->user) < 0)
658 die("ptrace(PTRACE_SETREGS): %m");
663 /*** Syscall checks ***/
666 valid_filename(arg_t addr)
668 char namebuf[4096], *p, *end;
672 err("FA: File access forbidden");
673 if (file_access >= 9)
678 sprintf(namebuf, "/proc/%d/mem", (int) box_pid);
679 mem_fd = open(namebuf, O_RDONLY);
681 die("open(%s): %m", namebuf);
688 int remains = PAGE_SIZE - (addr & (PAGE_SIZE-1));
689 int l = namebuf + sizeof(namebuf) - end;
693 err("FA: Access to file with name too long");
694 if (lseek64(mem_fd, addr, SEEK_SET) < 0)
695 die("lseek64(mem): %m");
696 remains = read(mem_fd, end, l);
698 die("read(mem): %m");
700 err("FA: Access to file with name out of memory");
707 msg("[%s] ", namebuf);
708 if (file_access >= 3)
711 // Everything in current directory is permitted
712 if (!strchr(namebuf, '/') && strcmp(namebuf, ".."))
715 // ".." anywhere in the path is forbidden
716 enum action act = A_DEFAULT;
717 if (strstr(namebuf, ".."))
721 for (struct path_rule *r = user_path_rules; r && !act; r=r->next)
722 act = match_path_rule(r, namebuf);
724 // Scan built-in rules
725 if (file_access >= 2)
726 for (int i=0; i<ARRAY_SIZE(default_path_rules) && !act; i++)
727 act = match_path_rule(&default_path_rules[i], namebuf);
730 err("FA: Forbidden access to file `%s'", namebuf);
733 // Check syscall. If invalid, return -1, otherwise return the action mask.
735 valid_syscall(struct syscall_args *a)
737 unsigned int sys = a->sys;
738 unsigned int act = (sys < NUM_ACTIONS) ? syscall_action[sys] : A_DEFAULT;
742 if (filter_syscalls != 1)
746 switch (act & A_ACTION_MASK)
753 valid_filename(a->arg1);
761 if (a->arg1 == (arg_t) box_pid)
763 meta_printf("exitsig:%d\n", (int) a->arg2);
764 err("SG: Committed suicide by signal %d", (int) a->arg2);
768 if (a->arg1 == (arg_t) box_pid && a->arg2 == (arg_t) box_pid)
770 meta_printf("exitsig:%d\n", (int) a->arg3);
771 err("SG: Committed suicide by signal %d", (int) a->arg3);
780 signal_alarm(int unused UNUSED)
782 /* Time limit checks are synchronous, so we only schedule them there. */
788 signal_int(int unused UNUSED)
790 /* Interrupts are fatal, so no synchronization requirements. */
791 meta_printf("exitsig:%d\n", SIGINT);
792 err("SG: Interrupted");
795 #define PROC_BUF_SIZE 4096
797 read_proc_file(char *buf, char *name, int *fdp)
803 sprintf(buf, "/proc/%d/%s", (int) box_pid, name);
804 *fdp = open(buf, O_RDONLY);
806 die("open(%s): %m", buf);
808 lseek(*fdp, 0, SEEK_SET);
809 if ((c = read(*fdp, buf, PROC_BUF_SIZE-1)) < 0)
810 die("read on /proc/$pid/%s: %m", name);
811 if (c >= PROC_BUF_SIZE-1)
812 die("/proc/$pid/%s too long", name);
821 struct timeval now, wall;
823 gettimeofday(&now, NULL);
824 timersub(&now, &start_time, &wall);
825 wall_ms = wall.tv_sec*1000 + wall.tv_usec/1000;
826 if (wall_ms > wall_timeout)
827 err("TO: Time limit exceeded (wall clock)");
829 fprintf(stderr, "[wall time check: %d msec]\n", wall_ms);
833 char buf[PROC_BUF_SIZE], *x;
834 int utime, stime, ms;
835 static int proc_stat_fd;
836 read_proc_file(buf, "stat", &proc_stat_fd);
838 while (*x && *x != ' ')
843 die("proc stat syntax error 1");
844 while (*x && (*x != ')' || x[1] != ' '))
846 while (*x == ')' || *x == ' ')
848 if (sscanf(x, "%*c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d", &utime, &stime) != 2)
849 die("proc stat syntax error 2");
850 ms = (utime + stime) * 1000 / ticks_per_sec;
852 fprintf(stderr, "[time check: %d msec]\n", ms);
853 if (ms > timeout && ms > extra_timeout)
854 err("TO: Time limit exceeded");
859 sample_mem_peak(void)
862 * We want to find out the peak memory usage of the process, which is
863 * maintained by the kernel, but unforunately it gets lost when the
864 * process exits (it is not reported in struct rusage). Therefore we
865 * have to sample it whenever we suspect that the process is about
868 char buf[PROC_BUF_SIZE], *x;
869 static int proc_status_fd;
870 read_proc_file(buf, "status", &proc_status_fd);
876 while (*x && *x != ':' && *x != '\n')
878 if (!*x || *x == '\n')
881 while (*x == ' ' || *x == '\t')
885 while (*x && *x != '\n')
891 if (!strcmp(key, "VmPeak"))
893 int peak = atoi(val);
894 if (peak > mem_peak_kb)
900 msg("[mem-peak: %u KB]\n", mem_peak_kb);
906 int syscall_count = (filter_syscalls ? 0 : 1);
911 bzero(&sa, sizeof(sa));
912 sa.sa_handler = signal_int;
913 sigaction(SIGINT, &sa, NULL);
915 gettimeofday(&start_time, NULL);
916 ticks_per_sec = sysconf(_SC_CLK_TCK);
917 if (ticks_per_sec <= 0)
918 die("Invalid ticks_per_sec!");
920 if (timeout || wall_timeout)
922 sa.sa_handler = signal_alarm;
923 sigaction(SIGALRM, &sa, NULL);
937 p = wait4(box_pid, &stat, WUNTRACED, &rus);
945 die("wait4: unknown pid %d exited!", p);
950 if (WEXITSTATUS(stat))
954 meta_printf("exitcode:%d\n", WEXITSTATUS(stat));
955 err("RE: Exited with error status %d", WEXITSTATUS(stat));
959 // Internal error happened inside the child process and it has been already reported.
963 if (timeout && total_ms > timeout)
964 err("TO: Time limit exceeded");
965 if (wall_timeout && wall_ms > wall_timeout)
966 err("TO: Time limit exceeded (wall clock)");
968 fprintf(stderr, "OK (%d.%03d sec real, %d.%03d sec wall, %d MB, %d syscalls)\n",
969 total_ms/1000, total_ms%1000,
970 wall_ms/1000, wall_ms%1000,
971 (mem_peak_kb + 1023) / 1024,
975 if (WIFSIGNALED(stat))
978 meta_printf("exitsig:%d\n", WTERMSIG(stat));
980 err("SG: Caught fatal signal %d%s", WTERMSIG(stat), (syscall_count ? "" : " during startup"));
982 if (WIFSTOPPED(stat))
984 int sig = WSTOPSIG(stat);
988 msg("[ptrace status %08x] ", stat);
989 static int stop_count;
990 if (!stop_count++) /* Traceme request */
991 msg(">> Traceme request caught\n");
993 err("SG: Breakpoint");
994 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
996 else if (sig == (SIGTRAP | 0x80))
999 msg("[ptrace status %08x] ", stat);
1000 struct syscall_args a;
1001 static unsigned int sys_tick, last_act;
1002 static arg_t last_sys;
1003 get_syscall_args(&a);
1005 if (++sys_tick & 1) /* Syscall entry */
1009 msg(">> Syscall %-12s (%08jx,%08jx,%08jx) ", syscall_name(sys, namebuf), (intmax_t) a.arg1, (intmax_t) a.arg2, (intmax_t) a.arg3);
1013 if (sys == __NR_execve)
1016 else if ((act = valid_syscall(&a)) >= 0)
1020 if (act & A_SAMPLE_MEM)
1026 * Unfortunately, PTRACE_KILL kills _after_ the syscall completes,
1027 * so we have to change it to something harmless (e.g., an undefined
1028 * syscall) and make the program continue.
1030 set_syscall_nr(&a, ~(arg_t)0);
1031 err("FO: Forbidden syscall %s", syscall_name(sys, namebuf));
1035 else /* Syscall return */
1037 if (sys == ~(arg_t)0)
1039 /* Some syscalls (sigreturn et al.) do not return a value */
1040 if (!(last_act & A_NO_RETVAL))
1041 err("XX: Syscall does not return, but it should");
1045 if (sys != last_sys)
1046 err("XX: Mismatched syscall entry/exit");
1048 if (last_act & A_NO_RETVAL)
1051 msg("= %jd\n", (intmax_t) a.result);
1053 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1055 else if (sig == SIGSTOP)
1057 msg(">> SIGSTOP\n");
1058 if (ptrace(PTRACE_SETOPTIONS, box_pid, NULL, (void *) PTRACE_O_TRACESYSGOOD) < 0)
1059 die("ptrace(PTRACE_SETOPTIONS): %m");
1060 ptrace(PTRACE_SYSCALL, box_pid, 0, 0);
1062 else if (sig != SIGXCPU && sig != SIGXFSZ)
1064 msg(">> Signal %d\n", sig);
1065 sample_mem_peak(); /* Signal might be fatal, so update mem-peak */
1066 ptrace(PTRACE_SYSCALL, box_pid, 0, sig);
1070 meta_printf("exitsig:%d", sig);
1071 err("SG: Received signal %d", sig);
1075 die("wait4: unknown status %x, giving up!", stat);
1080 box_inside(int argc, char **argv)
1085 memcpy(args, argv, argc * sizeof(char *));
1087 if (set_cwd && chdir(set_cwd))
1092 if (open(redir_stdin, O_RDONLY) != 0)
1093 die("open(\"%s\"): %m", redir_stdin);
1098 if (open(redir_stdout, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 1)
1099 die("open(\"%s\"): %m", redir_stdout);
1104 if (open(redir_stderr, O_WRONLY | O_CREAT | O_TRUNC, 0666) != 2)
1105 die("open(\"%s\"): %m", redir_stderr);
1113 rl.rlim_cur = rl.rlim_max = memory_limit * 1024;
1114 if (setrlimit(RLIMIT_AS, &rl) < 0)
1115 die("setrlimit(RLIMIT_AS): %m");
1118 rl.rlim_cur = rl.rlim_max = (stack_limit ? (rlim_t)stack_limit * 1024 : RLIM_INFINITY);
1119 if (setrlimit(RLIMIT_STACK, &rl) < 0)
1120 die("setrlimit(RLIMIT_STACK): %m");
1122 rl.rlim_cur = rl.rlim_max = 64;
1123 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
1124 die("setrlimit(RLIMIT_NOFILE): %m");
1126 char **env = setup_environment();
1127 if (filter_syscalls)
1129 if (ptrace(PTRACE_TRACEME) < 0)
1130 die("ptrace(PTRACE_TRACEME): %m");
1131 /* Trick: Make sure that we are stopped until the boxkeeper wakes up. */
1134 execve(args[0], args, env);
1135 die("execve(\"%s\"): %m", args[0]);
1141 fprintf(stderr, "Invalid arguments!\n");
1143 Usage: box [<options>] -- <command> <arguments>\n\
1146 -a <level>\tSet file access level (0=none, 1=cwd, 2=/etc,/lib,..., 3=whole fs, 9=no checks; needs -f)\n\
1147 -c <dir>\tChange directory to <dir> first\n\
1148 -e\t\tInherit full environment of the parent process\n\
1149 -E <var>\tInherit the environment variable <var> from the parent process\n\
1150 -E <var>=<val>\tSet the environment variable <var> to <val>; unset it if <var> is empty\n\
1151 -f\t\tFilter system calls (-ff=very restricted)\n\
1152 -i <file>\tRedirect stdin from <file>\n\
1153 -k <size>\tLimit stack size to <size> KB (default: 0=unlimited)\n\
1154 -m <size>\tLimit address space to <size> KB\n\
1155 -M <file>\tOutput process information to <file> (name:value)\n\
1156 -o <file>\tRedirect stdout to <file>\n\
1157 -p <path>\tPermit access to the specified path (or subtree if it ends with a `/')\n\
1158 -p <path>=<act>\tDefine action for the specified path (<act>=yes/no)\n\
1159 -r <file>\tRedirect stderr to <file>\n\
1160 -s <sys>\tPermit the specified syscall (be careful)\n\
1161 -s <sys>=<act>\tDefine action for the specified syscall (<act>=yes/no/file)\n\
1162 -t <time>\tSet run time limit (seconds, fractions allowed)\n\
1163 -T\t\tAllow syscalls for measuring run time\n\
1164 -v\t\tBe verbose (use multiple times for even more verbosity)\n\
1165 -w <time>\tSet wall clock time limit (seconds, fractions allowed)\n\
1166 -x <time>\tSet extra timeout, before which a timing-out program is not yet killed,\n\
1167 \t\tso that its real execution time is reported (seconds, fractions allowed)\n\
1173 main(int argc, char **argv)
1178 while ((c = getopt(argc, argv, "a:c:eE:fi:k:m:M:o:p:r:s:t:Tvw:x:")) >= 0)
1182 file_access = atol(optarg);
1191 if (!set_env_action(optarg))
1198 stack_limit = atol(optarg);
1201 redir_stdin = optarg;
1204 memory_limit = atol(optarg);
1210 redir_stdout = optarg;
1213 if (!set_path_action(optarg))
1217 redir_stderr = optarg;
1220 if (!set_syscall_action(optarg))
1224 timeout = 1000*atof(optarg);
1227 syscall_action[__NR_times] = A_YES;
1233 wall_timeout = 1000*atof(optarg);
1236 extra_timeout = 1000*atof(optarg);
1245 if (setreuid(uid, uid) < 0)
1246 die("setreuid: %m");
1251 box_inside(argc-optind, argv+optind);
1254 die("Internal error: fell over edge of the world");